我试图一遍又一遍地播放声音。我有以下代码:
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();
}
}
但是它只能播放一次声音。
答案 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();
}
}