John
John

Reputation: 194

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!");

});

Upvotes: 7

Views: 4400

Answers (1)

Johannes
Johannes

Reputation: 67758

You don't need the event listener, just:

var audio1 = document.getElementById("myAudio1");
audio1.onended = function() {
    alert("audio playback has ended");
};

Upvotes: 9

Related Questions