I'm integrated audio in a Java application. The problem is that sometimes clip.open() hangs up a little so I've read that I need to reload the clip and then just clip.start().
I'm using a sound class for each audio file, it reloads the clip once it has finish playing. The problem here is that the sound I trigger doesn't play right when I trigger it, but when I trigger the next sound. It shifts all sounds.
I've came up with the idea that it happens becouse the load method opens a clip that is then used by a different Sound instance, ¿Shoudn´t it just load it's clip?
Like I said, if a call the load method right after start, it freezes sometimes. I've created a thread to run it, so that it doesn't hang the main thread, but it freezes anyway so the sound plays late.
public class Sound {
private final String file;
private static Clip clip;
public Sound(String file){
this.file = file;
load();
}
public final void load(){
try {
AudioInputStream stream = AudioSystem.getAudioInputStream(new File(file).getAbsoluteFile());
clip = AudioSystem.getClip();
System.out.println(clip);
clip.open(stream);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
Logger.getLogger(Sound.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void play() {
clip.start();
clip.addLineListener(e -> {
if (e.getType() == LineEvent.Type.STOP) {
clip.stop();
clip.close();
load();
}
});
}
}
I expect the audio to played at the moment when it's triggered.