简体   繁体   中英

Close a looping javax.sound.sampled clip

I'm probably approaching this incorrectly but I need to find out how to stop a looping javax.sound.sampled clip. I have 9 different sounds. I want a different sound to play as a user presses an increase amplitude button. At the moment I'm calling the playSound method each time they click the button and it's working, however it's not stopping sounds that are already playing. The sounds just play over each other.

Is there a way to close all existing sounds when the user presses the 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's driving me mad. Any help would be much appreciated.

What you want is to stop all existing clips from playing. That can be done using the Dataline.stop() method. All you need is to be able to access all existing clips. Below is my suggestion. Note that I only use one reference to link to the currently looping clip. If you have more than one, use ArrayList<Clip> instead of only 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();
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM