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 pleted? I tried the "ended" property but the function is not being called after audio finished playing.
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 pleted? I tried the "ended" property but the function is not being called after audio finished playing.
Share Improve this question edited Apr 1, 2021 at 12:08 Mendy 8,7126 gold badges31 silver badges46 bronze badges asked Jul 25, 2017 at 9:34 Gobinath MGobinath M 2,0316 gold badges29 silver badges47 bronze badges 1-
1
Is it not just
onended
likemySound.onended = function(){ ... };
– Djave Commented Jul 25, 2017 at 9:39
3 Answers
Reset to default 6As @Djave notes in their ment, 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.
}
any ways to find when HTMLAudioElement audio pleted
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/en-US/docs/Web/Events/ended
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
})