所以这个while循环几乎什么都不做,直到我改变bgmPlaying的值。它工作正常。但是,如果我删除上面写着 //testing 的部分(没有任何换行符),它就不起作用。
这段代码实际上一直在检查音乐是打开还是关闭。
知道为什么当我删除 System.out.println() 部分时它停止工作吗???
这是我的代码:
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
/**
* This class simply plays a background music in a seperate thread
* @author Mohammad Nafis
* @version 1.0
* @since 04-03-2018
*
*/
public class AudioPlayer implements Runnable{
/**
* this boolean indicates whether the background music is playing
*/
private boolean bgmPlaying = true;
public void stopBGM() {
bgmPlaying = false;
}
public void playBGM() {
bgmPlaying = true;
}
/**
* this is an overridden method from Runnable interface that executes when a thread starts
*/
@Override
public void run() {
try {
File soundFile = new File("sounds/epic_battle_music.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = ais.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip clip = (Clip)AudioSystem.getLine(info);
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
//controlling the volume
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(-20);
clip.start();
while(true) {
if(bgmPlaying) {
gainControl.setValue(-20);
} else {
gainControl.setValue(-80);
}
while(bgmPlaying) {
//testing
System.out.println("BGM is on: ");
if(bgmPlaying == false) {
gainControl.setValue(-80);
break;
}
}
while(!bgmPlaying) {
//testing
System.out.println("BGM is off: ");
if(bgmPlaying == true) {
gainControl.setValue(-20);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码在我的 Controller 类中,它调用了 stop 和 play 方法。
//adding action listener
window.getpausebutton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
new Thread(new SoundEffect("sounds/clickSound.wav")).start();
bgm.stopBGM();
}
});
window.getplaybutton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
new Thread(new SoundEffect("sounds/clickSound.wav")).start();
bgm.playBGM();
}
});