I’m new to java and trying to add sound to my application. The problem I’m having is that the music starts but it doesn’t stop when the music method is called for the second time. What am I doing wrong?
import sun.audio.*;
import java.io.*;
public class sound {
private static boolean playing = false;
@SuppressWarnings("restriction")
public static void music() {
try {
// open the sound file as a Java input stream
String soundFile = "backgroundmusic.wav";
InputStream in = new FileInputStream(soundFile);
// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
if(playing == false){
AudioPlayer.player.start(audioStream);
playing = true;
}else{
AudioPlayer.player.stop(audioStream);
playing = false;
}
} catch(IOException error) {}
System.out.println(playing);
}
}
Every time you call
music(), a new input stream is constructed, so you are working with absolutely different stream instances between method calls.