我在试着一遍又一遍地播放声音。我有这样的代码:
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();
}
}但它只播放一次声音。
发布于 2020-08-05 07:27:03
clip.open(audioInputStream);
clip.start( );应该是:
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY); // <- NEW!
clip.start( );参数:
count -回放应该从循环的结束位置循环回到循环的开始位置的次数,或LOOP_CONTINUOUSLY,表示循环应该继续,直到中断
发布于 2020-08-04 22:14:14
您可能希望使用Clip#setFramePosition将剪辑的frame position设置为0。你会想要在Clip#start之前调用它。您还需要检查LineEvent类型是否是值LineEvent.Type#STOP,以确保事件是update事件或close,并且确实是在它停止的时候。
@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();
}
}https://stackoverflow.com/questions/63248747
复制相似问题