我是java的新手并试图为我的应用程序添加声音。我遇到的问题是音乐开始但是当第二次调用音乐方法时它不会停止。我做错了什么?
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);
}
}
答案 0 :(得分:3)
每次调用music()
时,都会构造一个新的输入流,因此您在方法调用之间使用绝对不同的流实例。