Marshal Alessi Marshal Alessi - 1 month ago 7
Java Question

Making a Global Audio Clip in Java

I'm working in a Java project where I play music as a main menu theme. I have it setup where I can play it, and I set it to loop. However, I need a way to be able to stop it at any time, presumably when the user leaves the main menu. The three sections commented out at the bottom were my feable attempt to call on a 'global' audio clip that was defined at the top. This will play the music, but it throws an un-initialized error with the else statement. How can I stop my audio within this function so that I can call it from other functions?

void AudioHandler1(String name, boolean play)
{
Clip clip;
if(play)
{
try
{
clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File((name)));
File file = new File(name);
inputStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();

clip.open(inputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
clip.start();
}
catch(Exception e)
{
System.out.println("Error: Can't locate sound.");
e.printStackTrace();
}
}
else
{
//clip = AudioSystem.getClip();
// AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File((name)));
//clip.stop();
}
}

Answer

I think here lies the problem:

else{
    clip = AudioSystem.getClip(); //<-- getclip() initialises a new clip which is not started yet ! 
    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File((name)));
    clip.stop(); // <-- your clip hasnt started yet so you cant stop it.
}

what you want to do is to save your Clip into a local variable to allow the access from other methods within the class.

try
    {
    clip = AudioSystem.getClip();
    this.clip = clip;
    ...
    }

    else
        {
        clip.stop();
        }

Furthermore you could create two static methods instead of your if/else systematic.

Clip audioClip = null;

public static void startSoundLoop(String name){
    try
        {
        clip = AudioSystem.getClip();
        this.audioClip = clip
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File((name)));
        File file = new File(name);
        inputStream = AudioSystem.getAudioInputStream(file);
        clip = AudioSystem.getClip();

        clip.open(inputStream);
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        clip.start();
        }
            catch(Exception e)
            {
                System.out.println("Error: Can't locate sound.");
                e.printStackTrace();
            }
}

public static void stopSoundLoop{
    this.clip.stop();
}