如何循环播放音频文件:在结束javax.sound.sampled之后再次播放

时间:2020-08-04 14:11:15

标签: java javasound

我试图一遍又一遍地播放声音。我有以下代码:

public void play()  {
        try  {
            URL defaultSound = getClass().getResource(filename);
            AudioInputStream audioInputStream =
                    AudioSystem.getAudioInputStream(defaultSound);
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start( );
            System.out.println(clip.getMicrosecondLength());
            Thread.sleep(clip.getMicrosecondLength() / 1000);
            clip.addLineListener(new LineListener() {
                @Override
                public void update(LineEvent event) {
                    try {
                        clip.start();
                        Thread.sleep(clip.getMicrosecondLength() / 1000);
                    }
                    catch (Exception e)  {
                        e.printStackTrace();
                    }
                }
            });

        }
        catch (Exception e)  {
            e.printStackTrace();
        }
    }

但是它只能播放一次声音。

2 个答案:

答案 0 :(得分:1)

clip.open(audioInputStream);
clip.start( );

应该是:

clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY); // <- NEW!
clip.start( );

请参见Clip.loop(int)

参数:
count-回放应从循环结束位置循环回到循环开始位置的次数,或LOOP_CONTINUOUSLY表示循环应持续到中断为止

答案 1 :(得分:0)

您可能希望使用Clip#setFramePosition将剪辑的frame position设置为0。您将需要在Clip#start之前调用它。您还需要检查LineEvent类型是否为值LineEvent.Type#STOP,以确保该事件是更新事件或关闭事件,并且确实是停止事件。

@Override
public void update(LineEvent event) {
    try {
        if (event.getType() == LineEvent.Type.STOP) {
            clip.setFramePosition(0);
            clip.start();
            Thread.sleep(clip.getMicrosecondLength() / 1000);
        }
    } catch (InterruptedException e)  {
        Thread.currentThread().interrupt();
    }
}