Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 286
fancy Avatar asked Feb 19 '12 04:02

fancy


People also ask

How do I know if audio is playing in HTML?

To check if audio is playing with JavaScript, we can use the paused property of the audio element. const isPlaying = (audElem) => { return !

How do you check if an audio is playing or not in JS?

The Audio tag has a paused property. If it is not paused, then it's playing.

Which event is used in the course to detect the end of video and implement playlist management?

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.


2 Answers

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

like image 131
Derek 朕會功夫 Avatar answered Sep 22 '22 20:09

Derek 朕會功夫


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/

like image 35
mauris Avatar answered Sep 21 '22 20:09

mauris