javascript 如何检测音频已在网页中播放完毕?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4619917/
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
How to detect an audio has finished playing in a web page?
提问by limc
In my project, I need to embed audio (ex: mp3, etc) into a web page. When user visits the page, the audio will begin playing. When the audio ends, the questionnaire (form fields) will appear for the user to answer.
在我的项目中,我需要将音频(例如:mp3 等)嵌入到网页中。当用户访问页面时,音频将开始播放。当音频结束时,将出现问卷(表单字段)供用户回答。
Is there is way to check if the audio has finished playing using jquery, so that the questionnaire can appear after the user has listened to the entire audio?
有没有办法使用jquery检查音频是否播放完毕,以便在用户听完整个音频后可以出现问卷?
I know one way to check is to determine the audio length, then I can set a timer to display the questionnaire, but I'm hoping jquery has some sort of event handler that allows me to accomplish this.
我知道一种检查方法是确定音频长度,然后我可以设置一个计时器来显示调查问卷,但我希望 jquery 有某种事件处理程序可以让我完成此任务。
I see that jquery has many audio plugins, and I can't be sure which will do what I want here: http://plugins.jquery.com/plugin-tags/audio
我看到 jquery 有很多音频插件,我不能确定哪个会做我想要的:http: //plugins.jquery.com/plugin-tags/audio
Any ideas are greatly appreciated.
任何想法都非常感谢。
Thanks.
谢谢。
回答by Adilson de Almeida Jr
If you are using the html5 audio tag, there is the "onended" event handler. I don′t know if the browsers support it yet.
如果您使用 html5 音频标签,则有“onended”事件处理程序。我不知道浏览器是否支持它。
Something like:
就像是:
<audio src="xpto.mp3" onended="DoSomething();"></audio>
In the last case you can use a swf that can play the sound, and alert your javascript when it reaches the end.
在最后一种情况下,您可以使用可以播放声音的 swf,并在播放结束时提醒您的 javascript。
回答by Justin Eldracher
You can also add a jQuery event listener like so:
您还可以像这样添加一个 jQuery 事件侦听器:
$("audio").on("ended", function() {
console.log("All Done!");
});
回答by NaxBuda
Using JavaScript event listener.
使用 JavaScript 事件监听器。
var myAudio = document.getElementById("myAudioId");
myAudio.addEventListener("ended", function() {
alert("The audio has ended.");
};

