How can I tell when an HTML5 audio element has finished playing?
How can I tell when an HTML5 audio element has finished playing?
Does it throw events I can listen to or something similar? I need to react when an audio track ends.
Thanks!
Solution 1:
Using HTML:
<audio id="music" src="blah.mp3" onended="yourFunction()"></audio>
Using Javascript:
document.querySelector("#music").addEventListener("ended", yourFunction, false);
Using jQuery:
$("#music").on("ended", yourFunction);
Read more about Media events on MDN
Solution 2:
According to W3Schools, you can use the onended
event to detect if the audio has finished playing.
In jQuery:
$("#player").bind('ended', function(){
// done playing
alert("Player stopped");
});
For a demonstration see: http://jsfiddle.net/9PCEf/2/