code prettify

Monday 13 October 2014

How do you know you have reached the end of an HTML5 audio?

It is very useful to know when an audio file has reached its end in the browser to indicate it visually.

To do so, we can attach an "ended" event on the HTML5 audio element, which happens when the audio reaches the end and stops playing. Using javascript, we can listen to this event and take necessary action.

Example:

<audio id="sample_audio" src="sample.mp3"></audio>

<script>
    var audio_elem = document.getElementById("sample_audio");

    audio_elem.addEventListener("ended", function() {
        alert("The audio file has finished playing");
    });
</script>

No comments:

Post a Comment