47

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!

fancy
  • 48,619
  • 62
  • 153
  • 231
  • Possible duplicate of [Is there an oncomplete event for HTML5 audio?](http://stackoverflow.com/questions/5092266/is-there-an-oncomplete-event-for-html5-audio) – Jannie Theunissen Dec 15 '15 at 07:41

2 Answers2

86

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

Joshua
  • 5,032
  • 2
  • 29
  • 45
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
31

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/

mauris
  • 42,982
  • 15
  • 99
  • 131