I have a .wav file I am trying to play. I am using this code:
public static synchronized void play(String path) {
try {
URL soundUrl = SoundTools.class.getResource(path);
AudioInputStream stream = AudioSystem.getAudioInputStream(soundUrl);
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
The code works well for a while, but after around 30 playbacks, I get a javax.sound.sampled.LineUnavailableException
. The error message says unable to obtain a line
. I believe that this has something to do with the system resources, but I do not know how I would go about fixing it.
You are never closing the Clip
which is a subclass of Line
that why you are receiving this error. Close the clip once you are done using close
method(that way you can free the resources) like this
clip.close();