最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find HTMLAudioElement audio ended playing - Stack Overflow

programmeradmin5浏览0评论

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 like mySound.onended = function(){ ... }; – Djave Commented Jul 25, 2017 at 9:39
Add a ment  | 

3 Answers 3

Reset to default 6

As @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
})
发布评论

评论列表(0)

  1. 暂无评论