Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering Event When Audio Has Finished Playing

I have not seen much documentation on the <audio> tag in HTML5. I am trying to trigger an event when audio has finished playing.

HTML:

<audio id="audio">
    <source src="'.$query['audioPronunciation'].'" type="audio/mp3">
    Your browser does not support the audio element.
</audio>

JavaScript / jQuery Play & Pause:

function audio() {
    if ($("#audioControl").hasClass("glyphicon-play")) {
        $("#audioControl").addClass("glyphicon-pause").removeClass("glyphicon-play");
        $("#audio").trigger("play");
    } else if ($("#audioControl").hasClass("glyphicon-pause")) {
        $("#audioControl").removeClass("glyphicon-pause").addClass("glyphicon-play");
        $("#audio").trigger("pause");
    }
}

JavaScript / jQuery, 'when ended'

$("#audio").addEventListener('ended', function() {
    alert("Audio has finished playing!");

});

like image 263
John Avatar asked Dec 13 '15 02:12

John


People also ask

How do you trigger an event on click?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event.

What triggers Javascript events?

onchange: It is triggered when an HTML element changes. onclick: It is triggered when an HTML element is clicked. onmouseover: It is triggered when the mouse is moved over a HTML element. onmouseout: It is triggered when the mouse is moved out of a HTML element.


1 Answers

You don't need the event listener, just:

var audio1 = document.getElementById("myAudio1");
audio1.onended = function() {
    alert("audio playback has ended");
};
like image 149
Johannes Avatar answered Sep 30 '22 03:09

Johannes