Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio Clip won't loop continuously

Tags:

java

javasound

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);
like image 424
daveed007 Avatar asked Jan 23 '12 23:01

daveed007


3 Answers

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
    }
}
like image 184
Paaske Avatar answered Nov 17 '22 10:11

Paaske


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.

like image 1
Lord Ashes Avatar answered Nov 17 '22 10:11

Lord Ashes


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.

like image 1
Firnaz Avatar answered Nov 17 '22 11:11

Firnaz