Reputation: 85
I have a sound class for my application and it plays a certain sound when I tell it too. I want to be able to detect when the sound is finished playing so I can then play a different sound without them over lapping here is my sound class:
public class Sound {
public static final Sound cash = new Sound("/cash.wav");
public static final Sound snap = new Sound("/snap.wav");
public static final Sound disarm = new Sound("/disarm.wav");
public static final Sound tp = new Sound("/tp.wav");
public static final Sound select = new Sound("/selectBTN.wav");
public static final Sound scroll = new Sound("/btn.wav");
public static final Sound fire = new Sound("/fire2.wav");
private AudioClip c;
public Sound(String filename) {
try {
c = Applet.newAudioClip(Sound.class.getResource(filename));
} catch (Exception e) {
e.printStackTrace();
}
}
public void play() {
try {
new Thread() {
public void run() {
if (!title.mute) {
c.play();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
then to play the sound I use this line of code:
Sound.cash.play();
How can I detect when the sound is finished playing
Upvotes: 1
Views: 497
Reputation: 2076
Try something like this (is an aproximation), with LineListener to detect the end of playing:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineEvent.Type;
import javax.sound.sampled.LineListener;
public class Sound {
private Clip c;
public Sound(final String filename) {
try {
c = AudioSystem.getClip();
final AudioInputStream inputStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream(filename));
c.open(inputStream);
c.addLineListener(new LineListener() {
@Override
public void update(final LineEvent event) {
if (event.getType().equals(Type.STOP)) {
System.out.println("Do something");
}
}
});
} catch (final Exception e) {
e.printStackTrace();
}
}
public void play() {
c.start();
}
public static void main(final String[] args) throws InterruptedException {
final Sound s = new Sound("/cash.wav");
s.play();
Thread.sleep(100000);
final Sound p = new Sound("/cash.wav");
p.play();
Thread.sleep(10000);
}
}
Upvotes: 1