Playing Sound in Java [duplicate] - java

This question already has answers here:
Access restriction error on my Java Code
(2 answers)
Closed 8 years ago.
Hello I'm trying to play a sound in java the code looks like this:
public void playSound(String sound) {
try {
InputStream in = new FileInputStream(new File(sound));
AudioStream audio = new AudioStream(in);
AudioPlayer.player.start(audio);
} catch (Exception e) {}
}
I imported sun.audio*; however get an error:
Access restriction: The type 'AudioPlayer' is not API (restriction on
required library 'C:\Program Files\Java\jre7\lib\rt.jar')

The following program plays a 16-bit wav sound from eclipse if we use javax.sound.
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {
// Constructor
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
// You could also get the sound file with a URL
File soundFile = new File("C:/Users/niklas/workspace/assets/Sound/sound.wav");
try ( // Open an audio input stream.
AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip()) {
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}

Related

.wav sounds not playing in Java

I am currently using this function to play .WAV files
public void playSound(String sound){
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource(sound);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
The problem is that no sound is being played when I call the function on a file, no errors or exceptions are thrown or whatsoever the program just starts and stops, no sound plays, I tried with a lot of different .WAV files with no success.
The programm stops before it has time to play the sound since start is non-blocking.
Try the following :
clip.start();
clip.drain();
clip.close();
This works for me:
public void sound() {
try{
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("./sounds/player-laser.wav"));
Clip test = AudioSystem.getClip();
test.open(ais);
test.loop(0);
}catch(Exception ex){
ex.printStackTrace();
}
}

Changing the output audio level of a program in Java within the program

I am trying to change the output audio levels of the program, preferably in decibels. I need to change the audio levels of the entire program and record the change in the level. The language is Java. Is there any easy way to do this? The sounds I am using to play the sounds is below:
import java.io.InputStream;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Sound
{
String sounds;
public Sound(String file)
{
sounds = file;
playSound(sounds);
}//end contructor
public void playSound(String soundLoc)
{
try
{
InputStream inputStream = getClass().getResourceAsStream(soundLoc);
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
}//end try
catch (Exception e)
{
}//end catch
}//end playSound method
}//end class Sound
You can use MASTER_GAIN_CONTROL using the Java sound API
you need to import this.... import javax.sound.sampled.*;
get your clip using a Clip object and then,
public void playSound(String soundLoc)
{
try
{
InputStream inputStream = getClass().getResourceAsStream(soundLoc);
AudioStream audioStream = new AudioStream(inputStream);
AudioPlayer.player.start(audioStream);
Clip myclip = AudioSystem.getClip();
myclip.open(audioStream);
FloatControl audioControl = (FloatControl) myclip.getControl(FloatControl.Type.MASTER_GAIN);
audioControl.setValue(-5.0f); //decrease volume 5 decibels
clip.start();
}//end try
catch (Exception e)
{
}//end catch
}//end playSound method

Can I call a .mp3 or .wav file from a Java package in NetBeans? [duplicate]

This question already has answers here:
How to read a file from jar in Java?
(6 answers)
Closed 8 years ago.
My friend asked me to create an app that he can use in conjunction with the game Plague Inc, and he wants the soundtrack from the game to play in the application. Upon doing web research I have tried everything and nothing works. Is it possible to call the soundtrack from a java package (like with an image) instead of specifying folder directories and URLs? There was some promising information I found online but when I ran the code after trying it, the AudioInputStream keeps on giving me errors. I have tried using the clauses exceptions but that severely conflicted with the main method and the application would not even run. I have tried putting the coding in the constructor, a new method and even in the main method itself but all of them just throw out errors when I run the application (I don't even know where to put it so that it will work). Please help as this is getting seriously frustrating.
My package is called Sound and the file is called plague.wav
And although the game is an Android game, my application runs off Windows PC
Here is the coding I have so far:
File sound = new File("/Sound/plague.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(sound);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (LineUnavailableException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedAudioFileException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
}
You can get it as a resource stream
Check this:
InputStream input = getClass().getResourceAsStream("/Sound/plague.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(input);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (LineUnavailableException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedAudioFileException ex) {
Logger.getLogger(knownDiseases.class.getName()).log(Level.SEVERE, null, ex);
}
Here's a sample class:
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class Snippet {
public static void main(String[] args) throws Exception {
try {
InputStream input = Snippet.class.getResource("/Sound/sound.wav")
.openStream();
AudioInputStream audioIn = AudioSystem.getAudioInputStream(input);
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Playing sound in a Java Desktop application

How do we play sound (a music file of any format like .wma, .mp3 ) in a Java desktop application? (not an applet)
I have used the following code (taken from another question on Stack Overflow) but it throws an Exception.
public class playsound {
public static void main(String[] args) {
s s=new s();
s.start();
}
}
class s extends Thread{
public void run(){
try{
InputStream in = new FileInputStream("C:\\Users\\srgf\\Desktop\\s.wma");
AudioStream as = new AudioStream(in); //line 26
AudioPlayer.player.start(as);
}
catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
The program when run throws the following Exception:
java.io.IOException: could not create audio stream from input stream
at sun.audio.AudioStream.<init>(AudioStream.java:82)
at s.run(delplaysound.java:26)
Use this library:
http://www.javazoom.net/javalayer/javalayer.html
public void play() {
String song = "http://www.ntonyx.com/mp3files/Morning_Flower.mp3";
Player mp3player = null;
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new URL(song).openStream());
mp3player = new Player(in);
mp3player.play();
} catch (MalformedURLException ex) {
} catch (IOException e) {
} catch (JavaLayerException e) {
} catch (NullPointerException ex) {
}
}
Hope that helps everyone with a similar question :-)
Hmmm. This might look like advertisement for my stuff, but you could use my API here:
https://github.com/s4ke/HotSound
playback is quite easy with this one.
Alternative: use Java Clips (prebuffering)
... code ...
// specify the sound to play
File soundFile = new File("pathToYouFile");
//this does the conversion stuff for you if you have the correct SPIs installed
AudioInputStream inputStream =
getSupportedAudioInputStreamFromInputStream(new FileInputStream(soundFile));
// load the sound into memory (a Clip)
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
// due to bug in Java Sound, explicitly exit the VM when
// the sound has stopped.
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
System.exit(0);
}
}
});
// play the sound clip
clip.start();
... code ...
Then you need this method:
public static AudioInputStream getSupportedAudioInputStreamFromInputStream(InputStream pInputStream) throws UnsupportedAudioFileException,
IOException {
AudioInputStream sourceAudioInputStream = AudioSystem
.getAudioInputStream(pInputStream);
AudioInputStream ret = sourceAudioInputStream;
AudioFormat sourceAudioFormat = sourceAudioInputStream.getFormat();
DataLine.Info supportInfo = new DataLine.Info(SourceDataLine.class,
sourceAudioFormat,
AudioSystem.NOT_SPECIFIED);
boolean directSupport = AudioSystem.isLineSupported(supportInfo);
if(!directSupport) {
float sampleRate = sourceAudioFormat.getSampleRate();
int channels = sourceAudioFormat.getChannels();
AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sampleRate,
16,
channels,
channels * 2,
sampleRate,
false);
AudioInputStream convertedAudioInputStream = AudioSystem
.getAudioInputStream(newFormat, sourceAudioInputStream);
sourceAudioFormat = newFormat;
ret = convertedAudioInputStream;
}
return ret;
}
Source for the Clip example (with little changes by me): http://www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm
SPIs are added via adding their .jars to the classpath
for mp3 these are:
http://www.javazoom.net/mp3spi/mp3spi.html
http://www.javazoom.net/javalayer/javalayer.html
http://www.tritonus.org/plugins.html (tritonus_share.jar)
Using JavaFX (which is bundled with your JDK) is pretty simple.
You will need the following imports:
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;
import java.nio.file.Paths;
Steps:
Initialize JavaFX:
new JFXPanel();
Create a Media (sound):
Media media = new Media(Paths.get(filename).toUri().toString());
Create a MediaPlayer to play the sound:
MediaPlayer player = new MediaPlayer(media);
And play the Media:
player.play();
You can set the start/stop times as well with MediaPlayer.setStartTime() and MediaPlayer.setStopTime():
player.setStartTime(new Duration(Duration.ZERO)); // Start at the beginning of the sound file
player.setStopTime(1000); // Stop one second (1000 milliseconds) into the playback
Or, you can stop playing with MediaPlayer.stop().
A sample function to play audio:
public static void playAudio(String name, double startMillis, double stopMillis) {
Media media = new Media(Paths.get(name).toUri().toString());
MediaPlayer player = new MediaPlayer(media);
player.setStartTime(new Duration(startMillis));
player.setStopTime(new Duration(stopMillis));
player.play();
}
More info can be found at the JavaFX javadoc.

error playing sound java (No line matching interface Clip supporting format)

We are trying to integrated sound in one of our project, my team members don't get this error, and I get it on two different machines.
Stack trace:
Exception in thread "SoundPlayer" java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED 16000.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian, and buffers of 11129272 to 11129272 bytes is supported.
at javax.sound.sampled.AudioSystem.getLine(Unknown Source)
at sound.Music.run(Music.java:86)
at java.lang.Thread.run(Unknown Source)
Code:
package sound;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Music implements LineListener, Runnable
{
private File soundFile;
private Thread thread;
private static Music player;
private Music audio;
private Clip clip;
public Music()
{
}
public void playSiren(String musicFileName)
{
Music p = getPlayer();
p.playSirenFile(musicFileName);
}
private void playSirenFile(String musicFileName)
{
this.soundFile = new File("Music/"+musicFileName+".wav");
thread = new Thread(this);
thread.setName("SoundPlayer");
thread.start();
}
public void run()
{
try
{
AudioInputStream stream = AudioSystem.getAudioInputStream(this.soundFile);
AudioFormat format = stream.getFormat();
/**
* we can't yet open the device for ALAW/ULAW playback, convert
* ALAW/ULAW to PCM
*/
if ((format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW))
{
AudioFormat tmp = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2, format.getChannels(),
format.getFrameSize() * 2, format.getFrameRate(), true);
stream = AudioSystem.getAudioInputStream(tmp, stream);
format = tmp;
}
DataLine.Info info = new DataLine.Info(Clip.class, stream
.getFormat(), ((int) stream.getFrameLength() * format
.getFrameSize()));
clip = (Clip) AudioSystem.getLine(info);
clip.addLineListener(this);
clip.open(stream);
clip.start();
try
{
thread.sleep(99);
}
catch (Exception e)
{
}
while (clip.isActive() && thread != null)
{
try
{
thread.sleep(99);
}
catch (Exception e)
{
break;
}
}
clip.loop(99999999);
}
catch (UnsupportedAudioFileException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (LineUnavailableException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Music getPlayer()
{
if (player == null)
{
player = new Music();
}
return player;
}
public void update(LineEvent event)
{
}
public void stopClip()
{
clip.stop();
}
public void closeClip()
{
clip.close();
}
public void startClip()
{
clip.start();
}
public void volume(float volume)
{
/*
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(-50.0f); // Reduce volume IN DECIBELS
clip.start();
*/
}
}
We call this class from domainController with
audio = new Music();
audio.playSiren("stillAliveDecent");
does Anyone have an idea how this exception can be resolved?
I tried reinstalling my editor software (Eclipse) but to no avail.
thanks allot in advance.
Edit
We just tried switching the sound file. We tried running it with much smaller file. this now works, but once we switch back to the larger .wav file (10+MB) I get the exception again.
Only using smaller files is not really an option as we would like to use some self made songs which are quite long.
Edit 2
I'm quite sure it isn't a corrupted wav. we recompiled it, even used another wave of similar length and size, and i'm still the only one getting this error.
some extra requested info:
OS: Windows 7 64bit Ultimate
JDK: 1.6.0_22
Edit 3
After some wave creating and playing we have come to the conclusion that for some reason I can't play wave's larger than 2MB.
Still why aren't my teammates affected by this?
I was experiencing this same problem on a raspberry pi. It would play the first 5 files just fine, then I'd get the error. It turned out that I was not closing the clip when I needed to.
Clip clip = AudioSystem.getClip();
clip.addLineListener(event -> {
if(LineEvent.Type.STOP.equals(event.getType())) {
clip.close();
}
});
ByteArrayInputStream audioBytes = new ByteArrayInputStream(SOUNDS.get(file));
AudioInputStream inputStream = AudioSystem.getAudioInputStream(audioBytes);
clip.open(inputStream);
clip.start();
After adding the line listener and closing the clip when it stopped, the errors went away.
You can actually play sound above 40 mb, if needed, thats how far i went :p, the problem is mostly eclipse, and to be more exact its the .metadata folder in your workspace i think its like a small plugin that only gets uploaded half of the time, so the problem lies with your editor and not the code, the code above is working perfectly since i could play songs without any trouble. Make sure your paths are correct, and try to get a correct version of the .metadata and you should be fine. A friend of mine had the same problem, and i gave him my copy of the workspace and .metadata and it worked perfectly.

Categories