单击按钮时如何防止声音重叠?

时间:2019-01-19 01:03:58

标签: java javasound

问题描述:我有一系列长度不同的声音文件。每次单击Play按钮时,我要播放一种声音。问题是,当单击Play按钮两次(或更多次)时,下一个声音开始并且与当前播放的声音重叠。我不想clip.stop()当前的声音,我希望下一个声音在当前声音结束之前不开始。我尝试了各种方法,例如boolean flagclickCount和检查Clip.isRunning();的状态,但是它们并没有真正使我到达我想要的位置。我还看到其他人在OS中也有类似的问题(尽管使用MultiPlayer()),但是他的问题在AFAIK中得到了解决。任何建议,将不胜感激!

这里是相关代码:

public class PlaySounds {
private AudioInputStream audioStream;
public static Clip clip;
private URL url;
public static int nextSound;

public void playAllSounds() {
    for (String str : soundList) { // arrayList of sounds
        str = soundList.get(nextSound);
        url = getClass().getResource(str);
    }
    try {

        audioStream = AudioSystem.getAudioInputStream(url);
        clip = AudioSystem.getClip();
        clip.open(audioStream);
        clip.start();

    } catch (Exception e) {
    }

 }
}

主类文件:

PlaySounds ps = new PlaySounds();
int next = 0;
List<Integer> positions = new ArrayList<>();
 /*Some other methods....
....
*/
    private void getshuffledPositions() {

    for (int i = 0, i <=12; i++) {
        positions.add(i);

    }
    Collections.shuffle(positions);

}
public void actionPerformed(ActionEvent ae) {

    if (ae.getSource() == playButton) {
        //Some codes.....Here I tried boolean flag, etc
        ps.nextSound = positions.get(next);
        ps.playAllSounds();
        //Some more codes.....

0 个答案:

没有答案