Close the javax.sound.sampled clip loop

I probably approached this the wrong way, but I need to figure out how to stop the javax.sound.sampled clip loop. I have 9 different sounds. I want a different sound to play when the user presses the amplitude increase button. Currently I am calling the playSound method every time the button is pressed and it works but does not stop sounds that are already playing. The sounds just play on top of each other.

Is there a way to close all existing sounds when the user clicks a button?

Here's my playSound code:

    public void playSound(){
    try {
        audio = AudioSystem.getAudioInputStream(soundFile[activeSound]);
        clip = AudioSystem.getClip();
        clip.open(audio);
        clip.start();
        clip.loop(Clip.LOOP_CONTINUOUSLY);           
    }

    catch (IOException ex){
        System.out.println("Sorry but there has been a problem reading your file.");
        ex.printStackTrace();
    }

    catch (UnsupportedAudioFileException ex1){
        System.out.println("Sorry but the audio file format you are using is not supported.");
        ex1.printStackTrace();
    }

    catch (LineUnavailableException ex2){
        System.out.println("Sorry but there are audio line problems.");
        ex2.printStackTrace();
    } 
}

      

I've been at this for two days now and it was driving me crazy. Any help would be much appreciated.

+3


source to share


1 answer


You want to stop playing all existing clips. This can be done using the Dataline.stop () method . All you need is access to all existing clips. Below is my suggestion. Please note that I am only using one link to link to the current clip. If you have more than one, use ArrayList<Clip>

instead of one.



private Clip activeClip;
public void playSound(){
    activeClip.stop();
    try {
        audio = AudioSystem.getAudioInputStream(soundFile[activeSound]);
        clip = AudioSystem.getClip();
        clip.open(audio);
        clip.start();
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        activeClip = clip;
    }

    catch (IOException ex){
        System.out.println("Sorry but there has been a problem reading your file.");
        ex.printStackTrace();
        }

    catch (UnsupportedAudioFileException ex1){
        System.out.println("Sorry but the audio file format you are using is not     supported.");
        ex1.printStackTrace();
    }

    catch (LineUnavailableException ex2){
        System.out.println("Sorry but there are audio line problems.");
        ex2.printStackTrace();
    } 
}

      

+1


source







All Articles