Javascript 您如何检测 HTML5 音频何时完成播放(不止一次)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11103582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:28:10  来源:igfitidea点击:

How do you detect when HTML5 audio has finished playing (more than once)?

javascriptjqueryhtmlaudio

提问by evenodd

I am having a problem detecting when an tag is finished playing an mp3. When I do something like this:

我在检测标签何时播放完 mp3 时遇到问题。当我做这样的事情时:

     myAudio.addEventListener("ended", function() 
     {
          alert("ended");
     });

It only occurs the first time the audio is played. When I play the audio again, nothing happens. The same thing happens when I use the onended=doThis();method. I've heard maybe there is a way to do it in jQuery, but I haven't been able to get it to work. I've also heard there might be a way to fix it by changing the audio div idevery time the mp3 is played, but this doesn't work for me because I need the idto stay the same.

它仅在第一次播放音频时发生。当我再次播放音频时,没有任何反应。当我使用该onended=doThis();方法时会发生同样的事情。我听说也许有一种方法可以在 jQuery 中做到这一点,但我一直无法让它工作。我还听说可能有一种方法可以通过id每次播放 mp3 时更改音频 div 来修复它,但这对我不起作用,因为我需要id保持不变。

Did anyone get any ideas?

有没有人有任何想法?

回答by Cristi Pufu

The endedevent is created based on .currentTimeattribute. http://w3c.github.io/html/semantics-embedded-content.html#eventdef-media-ended

ended基础上创建的事件.currentTime属性。 http://w3c.github.io/html/semantics-embedded-content.html#eventdef-media-ended

So, all you have to do is set the .currentTimeto zero again.

因此,您所要做的就是.currentTime再次将 设置为零。

myAudio.addEventListener("ended", function(){
     myAudio.currentTime = 0;
     console.log("ended");
});