45

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
  • 44,977
  • 57
  • 150
  • 228
  • 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

83

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
  • 4,324
  • 2
  • 27
  • 43
Derek 朕會功夫
  • 88,688
  • 41
  • 174
  • 241
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
  • 41,504
  • 15
  • 94
  • 130