I have recently been learning how to add sounds in java. Currently, I have this code that works, but it isn't always playing at the right time, or sometimes it doesn't even play at all. How could I get the sound to play each time the play()
method is fired at the right timing? This happens every time I click
on a component
, by the way.
public class Sound {
private File sndFile0;
private AudioInputStream au;
private Clip cl;
private DataLine.Info info;
public Sound() {
try {
sndFile0 = new File(getClass().getResource("/sound/vir1.wav").toURI());
au = AudioSystem.getAudioInputStream(sndFile0);
info = new DataLine.Info(Clip.class, au.getFormat());
cl = (Clip) AudioSystem.getLine(info);
cl.open(au);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException | URISyntaxException e) {
e.printStackTrace();
}
}
public void play() {
cl.start();
cl.setFramePosition(0);
}
}