我可能处理得不正确,但我需要找出如何停止循环javax.sound.sampled片段。我有9种不同的声音。我想播放一个不同的声音作为用户按下一个增加振幅按钮。目前,我正在调用playsound方法,每次他们点击按钮,它是工作的,但它并没有停止已经播放的声音。这些声音只是互相干扰。
有没有办法关闭所有现有的声音当用户按下按钮?
这是我的PlaySound代码:

    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();
    }
}

我已经干了两天了,这让我很生气。任何帮助都将不胜感激。

最佳答案

您想要的是停止所有现有的剪辑播放。这可以使用Dataline.stop()方法完成。您所需要的就是能够访问所有现有的剪辑。下面是我的建议。注意,我只使用一个引用链接到当前循环剪辑。如果有多个,请使用ArrayList<Clip>而不是仅使用一个。

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();
    }
}

10-07 19:01
查看更多