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!
To check if audio is playing with JavaScript, we can use the paused property of the audio element. const isPlaying = (audElem) => { return !
The Audio tag has a paused property. If it is not paused, then it's playing.
The ended event occurs when the audio/video has reached the end. This event is useful for messages like "thanks for listening", "thanks for watching", etc.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With