Reputation: 35
So I have this class that plays background music in my java game on netbeans. I just want some ideas on how I could stop the sound if my character dies. I tried making a public boolean isCollided variable but for whenever my character collides with another object but it didn't work. I am open to suggestions.
import controller.Main;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public static boolean isCollided = false;
public static void play(String filename) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Main.class.getResourceAsStream(filename)));// new
// File(filename)));
if (isCollided) {
clip.stop();
} else {
clip.loop(0);
}
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
}).start();
}
Upvotes: 0
Views: 2903
Reputation: 567
have you tried using
clip.stop();
https://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/DataLine.html#stop()
I see you made some edits. Since you are running the clip in a thread, you'd need to have some way of interacting with the thread from your main method. Otherwise it just checks isCollided when the thread starts and never checks for changes.
One way would be to make isCollided a global variable and then have an infinite loop in the clip thread that checks for isCollided and stops when it becomes true. Something (with your variables) like
while (true) {
if (isCollided) {
clip.stop();
thread.interupt();
}
}
ETA: This is very processor intensive. You maybe could add a little delay like
while (true) {
Thread.sleep(500);
if (isCollided) {
clip.stop();
thread.interupt();
}
}
to keep it from bogging down your processor too much.
Upvotes: 1