Search code examples
javaaudiojavasound

Java - Playing a sound on top of background music


This is my first time posting, and hopefully I'm posting correctly.

I'm currently playing a background song for my project, and I'm trying to play a sound effect, when a button is pressed, on top of the background song. However, the sound doesn't play and the bgm just continues. See below for my Audio class (ignore the bad commenting), and thanks in advance for the help.

package pro;

import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Audio
{
    private boolean loop = false;
    private AudioInputStream ais = null;
    private static Clip clip = null;
    //declaration of variables

    public Audio (String fileName, boolean loop)
    //Constructor for the class which fileName and accepts whether the clip needs to loop or not
    {
        this.loop = loop;
        //sets the variable within the class as constructor 

        try {
            clip = AudioSystem.getClip();
            ais = AudioSystem.getAudioInputStream(Audio.class.getResource(fileName));
            clip.open(ais);

        } catch (IOException | UnsupportedAudioFileException | LineUnavailableException e) {
            e.printStackTrace();
        }
        //tries to load file into java's built in audio player, else prints the error to console
    }

    public void musicStart ()
    //starts music
    {
        if (loop)
        {
            clip.loop(Clip.LOOP_CONTINUOUSLY);
            //starts music on loop if loop is requested
        }
        else
        {
            clip.start();
            //starts music as not on loop
        }

    }


    public void musicStop ()
    //stops the music
    {
        clip.stop();
    }

}

EDIT: I found a solution to the problem thanks to MadProgrammer by simply removing static from clip.


Solution

  • Get rid of the static declaration of the Clip. Each instance of Audio should be self contained and point to it's own instance of Clip

    Basically, the static will make Clip ALWAYS point to the last sound file loaded, this isn't really what you want, because when you call stopMusic, you won't know which clip you're really stopping or if you're actually stopping anything at all