I'm making a game in Java and I want a theme song to play in the background, but every time the user presses minus the volume decreases. No matter what I try, I can't do this from another method besides the one where I initialized the Clip because the cli.
This is the code for my GameAudio class:
public class GameAudio {
private static float volume = -20.0f;
private Clip clip;
public GameAudio(String audioLocation) {
try {
File filePath = new File(audioLocation);
if (filePath.exists()) {
AudioInputStream audioInput = AudioSystem.getAudioInputStream(filePath);
Clip clip = AudioSystem.getClip();
clip.open(audioInput);
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(getVolume());
clip.loop(Clip.LOOP_CONTINUOUSLY);
clip.start();
} else {
System.out.println("Incorrect audio file path!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public float getVolume() {
return volume;
}
public void setVolume(float volume) {
GameAudio.volume = volume;
}
public void stopSound() {
clip.stop();
clip.close();
}
}
In my Player class I put:
private String musicPath = "maintheme.wav";
GameAudio gameAudio = new GameAudio(musicPath);
and then further down
if (input.minus.isPressed()) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
gameAudio.stopSound();
if (gameAudio.getVolume() <= -80.0f) {
gameAudio.setVolume(-70.0f);
}
gameAudio.setVolume(gameAudio.getVolume() - 10.0f);
System.out.println("Volume: " + gameAudio.getVolume());
}
When in debug mode the null pointer exception seems to come from gameAudio.stopSound() calling clip.stop(); and clip.close(); How can I avoid this?