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!

1

2 Answers 2

88

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

Sign up to request clarification or add additional context in comments.

1 Comment

This should be the answer.
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/

5 Comments

...relax man, I couldn't accept the answer yet because enough time hadn't passed yet. I hate when people leave comments like this.
Wow @thephpdeveloper, you are really thirsty for the tick!
guys. i was just reminding. i tend to forget on my end and therefore i remind whenever i post an answer. even if it is an answer posted by somebody else i'll remind too. that's what we are doing: moderating our community.
@thephpdeveloper, would you like to give that tick to me? I really want it... just joking.
onEnded in React

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.