Repeated audio clip not playing - Java

Raptor_Guy

I have a scheduled thread that runs every half-second or so and plays an audio clip each time, calling stop() on the clip before each cycle in order to start() it again:

public AudioThread() {
    Clip clipF5 = AudioSystem.getClip();
    AudioInputStream inputF5 = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("sound.wav"));
    clipF5.open(inputF5);
}

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

exec.scheduleAtFixedRate(new Runnable() {
    public void run() {
        if (clipF5.isRunning()) { clipF5.stop(); }

        clipF5.start();
    }
}, 1, interval, TimeUnit.MICROSECONDS);

But it doesn't play again after the first time. The code runs, but the sound doesn't play. Any ideas?

Phil Freihofner

Easy to fix!

You just need to add the step of resetting the media position. You can do this with either clip.setFramePosition(0) or clip.setMicrosecondPosition(0) to go back to the beginning of the clip. The start() method simply starts from the last media position, even if it is the end of the file.

if (clipF5.isRunning()) 
{
    clipF5.stop(); 
    clipF5.setFramePosition(0);
}

clipF5.start();

I'm assuming the length of your clip is less than 30 seconds!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive