我怎么知道HTML5音频元素何时结束播放?

时间:2021-02-07 15:21:50

How can I tell when an HTML5 audio element has finished playing?

我怎么知道HTML5音频元素何时结束播放?

Does it throw events I can listen to or something similar? I need to react when an audio track ends.

它会抛出一些我能听到的事件或者类似的事情吗?我需要在音轨结束时做出反应。

Thanks!

谢谢!

2 个解决方案

#1


27  

According to W3Schools, you can use the onended event to detect if the audio has finished playing.

根据W3Schools,你可以使用onended事件来检测音频是否已经完成播放。

In jQuery:

jQuery:

$("#player").bind('ended', function(){
    // done playing
    alert("Player stopped");
});

For a demonstration see: http://jsfiddle.net/9PCEf/2/

有关演示,请参见:http://jsfiddle.net/9PCEf/2/

#2


54  

Using HTML:

使用HTML:

<audio id="music" src="blah.mp3" onended="yourFunction()"></audio>

Using Javascript:

使用Javascript:

document.querySelector("#music").addEventListener("ended", yourFunction, false);

Using jQuery:

使用jQuery:

$("#music").on("ended", yourFunction);

Read more about Media events on MDN

阅读更多关于MDN上的媒体事件

#1


27  

According to W3Schools, you can use the onended event to detect if the audio has finished playing.

根据W3Schools,你可以使用onended事件来检测音频是否已经完成播放。

In jQuery:

jQuery:

$("#player").bind('ended', function(){
    // done playing
    alert("Player stopped");
});

For a demonstration see: http://jsfiddle.net/9PCEf/2/

有关演示,请参见:http://jsfiddle.net/9PCEf/2/

#2


54  

Using HTML:

使用HTML:

<audio id="music" src="blah.mp3" onended="yourFunction()"></audio>

Using Javascript:

使用Javascript:

document.querySelector("#music").addEventListener("ended", yourFunction, false);

Using jQuery:

使用jQuery:

$("#music").on("ended", yourFunction);

Read more about Media events on MDN

阅读更多关于MDN上的媒体事件