Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java .wav playback fails after multiple playbacks

Tags:

java

url

audio

clip

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.

like image 312
Jerfov2 Avatar asked Apr 11 '26 10:04

Jerfov2


1 Answers

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();
like image 161
sol4me Avatar answered Apr 12 '26 23:04

sol4me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!