How to find HTMLAudioElement audio ended playing

Viewed 2107

An application is playing an audio clip with the HTMLAudioElement in JavaScript like below,

mySound = new Audio([URLString]);

The URL string will keep on changing based on user clicks.

Any ways to find when HTMLAudioElement audio completed? I tried the "ended" property but the function is not being called after audio finished playing.

3 Answers

As @Djave notes in their comment, and as mentioned here, you can use the onended event for Audio objects created with JS (as opposed to ended, which is valid if you're using DOM elements):

mySound = new Audio(audioFile);
mySound.onended = function() {
    // Whatever you want to do when the audio ends.
}

You can use addEventListener and listen to the ended event just like when the HTMLAudioElement is in the DOM, e.g.

mySound = new Audio([URLString]);
mySound.addEventListener("ended", function(e) {
    // do whatever
})
Related