Reputation: 2021
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.
Upvotes: 4
Views: 3358
Reputation: 8633
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
})
Upvotes: 0
Reputation: 2022
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.
}
Upvotes: 6
Reputation: 29453
any ways to find when HTMLAudioElement audio completed
You can use the ended
Event Listener:
HTML:
<audio>
<source src="/my-audio-clip.mp3" type="audio/mpeg">
</audio>
Javascript:
var myAudioClip = document.querySelector('[src="/my-audio-clip.mp3"]');
myAudioClip.addEventListener('ended', myFunction, false);
Further Reading: https://developer.mozilla.org/en-US/docs/Web/Events/ended
Upvotes: 1