0

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?

VArchive
  • 13
  • 3

1 Answers1

2

Your problem is on this line:

            Clip clip = AudioSystem.getClip();

This is creating a local variable, and not setting the clip to the member variable you are using below.

Instead, try:

            clip = AudioSystem.getClip();
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Thanks so much! I have no idea how I missed that and spent **hours** trying to fix it without trying that lol. I also had to create a method to start the audio again because apparently I forgot that and it just stops the audio. Very helpful! :) – VArchive Apr 28 '20 at 18:15
  • @VArchive excellent! Please check the arrow on the left side of the answer to mark this question as answered – ControlAltDel May 01 '20 at 00:09