Java stop sound when another sound is starting to play

88 Views Asked by At

I'm Trying to make java game and now I'm implementing music to the game. Problem is if music is playing and sound is starting to play then I want to stop music.

Current Code

Clip clip;

public void playSound(File sound) {
    try {
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(sound));
        clip.start();
    } catch(Exception e) {
        System.out.println("Error with playing sound.");
        e.printStackTrace();
    }
}

public void stopSound() {
    if(clip == null) return;
    clip.stop();
}

But if I call stopSound method then sound never get's stopped.

Any help is appreciated!

1

There are 1 best solutions below

0
On BEST ANSWER

The scope of clip is the problem. The clip object defined in playSound is unknown to stopSound.

If your object contain a clip attribute, try to change the first line of playSound to:

clip = AudioSystem.getClip();