So this while loop pretty much do nothing until I change the value of bgmPlaying. It works fine. However, if I delete the parts that says //testing above it(without any line breaks), it does not work.
This block of code actually keeps checking whether a music is on or off.
Any idea why it stops working when I delete the System.out.println() parts???
Here is my code:
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();
}
}
}
This code is in my Controller class that calls the stop and play methods.
//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();
}
});