Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
670 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...