简体   繁体   中英

Audio Clip won't loop continuously

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);

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
    }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM