drenl
drenl

Reputation: 1333

Restart HTML5 audio element before it completes (JS: setTimeout)

This JS code refers to an HTML5 Audio element that plays a 4-second .mp3:

function playTone(){
    document.getElementById('tone').play();
};
setTimeout(playTone,2000);
setTimeout(playTone,7000);

This works to play the tone twice. However, if I set the second setTimeout to 3000 (which I would like to do) it only plays once, because the first mp3 has not finished playing. Is there a way get around this? How can I get the Audio element to restart from the beginning before it has completed?

For my purposes, I would like to call the same element, rather than dynamically creating a new one. The context is that I would like a selection of these audio elements on the page, and use JS to play them as a musical instrument.

Upvotes: 1

Views: 173

Answers (1)

Zach Johnson
Zach Johnson

Reputation: 152

You have to set the current time of the audio to the beginning before you play the audio. This function should work.

function playTone(){
    var tone = document.getElementById('tone');
    tone.currentTime = 0;
    tone.play();
}

Upvotes: 2

Related Questions