3

我可能不正确地处理这个问题,但我需要找出如何停止循环 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();
    } 
}

我已经在这里待了两天了,这让我很生气。任何帮助将非常感激。

4

1 回答 1

1

您想要的是停止播放所有现有剪辑。这可以使用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();
    } 
}
于 2012-04-10T12:16:37.710 回答