Audio Clip won't loop continuously

谁说我不能喝 提交于 2019-12-29 07:01:52

问题


Can anyone point me in the right direction as to why this code will not play this audio clip continuously? It plays it once and stops.

final Clip clip = AudioSystem.getClip();
final AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("Alarm_Police.wav"));
clip.open(inputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);

回答1:


If you are running a bigger application, this answer may not apply. But for a simple test with only that piece of code, this may help:

Clip.loop() starts it's own thread, but that thread will not keep the JVM alive. So to make it work, make sure the clip is not the only thread.

If I leave out Thread.sleep(..) from this snippet, I get the same issue as you;

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Snippet {
    public static void main(String[] args) throws Exception {

        AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("notify.wav"));
        Clip clip = AudioSystem.getClip();
        clip.open(inputStream);
        clip.loop(Clip.LOOP_CONTINUOUSLY);
        Thread.sleep(10000); // looping as long as this thread is alive
    }
}



回答2:


In order to play the complete audio file you would need to know the length of time to sleep. An alternative would be to:

while(clip.isRunning())
{
  Thread.sleep(100);
}

This keeps sleeping (in 100ms increments) until the isRunning() state has turned to false. You may need an initial sleep before this loop so that the isRunning() state has time to set.




回答3:


My audio file contains 20 seconds of an alarm beep. I need it continuously to ring. Instead of using thread, i went on with the piece of code shown below.

        while(true){
            clip.start();
            clip.loop(clip.LOOP_CONTINUOUSLY);              
        } 

Think this would help. Thanks.



来源:https://stackoverflow.com/questions/8979914/audio-clip-wont-loop-continuously

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!