Java.wav playback quits after multiple replays

I have a .wav file that 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 about 30 replays, I get javax.sound.sampled.LineUnavailableException

. The error message states unable to obtain a line

. I believe it has something to do with system resources, but I don't know how to do it.

+3


source to share


1 answer


You never close Clip

which subclass Line

is why you are getting this error. Close the clip as soon as you are done using a method close

(this way you can free up resources) like this



clip.close();

      

+2


source







All Articles