How to trigger a JQuery event when Audio has finished playing HTML5

11,838

Solution 1

Try this:

audio.addEventListener('ended', function(){
    $("#toggleButton").html("Play");
});

Solution 2

Your audio tag should trigger an "onended" event when the sound is complete. Hook on to that event, and update your button graphic as appropriate. Browser support, as always, may vary.

Share:
11,838
user1574598
Author by

user1574598

Updated on July 13, 2022

Comments

  • user1574598
    user1574598 almost 2 years

    I'm trying to fathom out how to trigger an event when my audio has stopped playing. I am using the HTML5 <audio> tag. So far I can get the audio to give me its duration using the duration property, but I'm unable to do much with this at the moment. All's I want to do is pass a "play" string into a html() method so it doesn't keep displaying "pause" when my audio is finished playing.

    Toggle function:

    $("#toggleButton").on("click", function(evt) {
        if(audio.paused) {
            audio.play();
            $(this).html("Pause");
        }
        else {
            audio.pause();
            $(this).html("Play");
        }
    });
    

    I am also struggling to find documentation regarding audio methods and properties. I've tried searching "audio" on both the JQuery and Mozilla network and they return nothing back.

  • user1574598
    user1574598 over 10 years
    Excellent! Works very nicely. I wrote it slightly different using the on('ended', function()...) method if that is okay? Will also check out your link too :-)
  • Sergio
    Sergio over 10 years
    @user1574598, like that you use jQuery. My version is plain javascript. Use as you wish.
  • Tales
    Tales over 6 years
    Fantastic tip. I really did research on this one