简体   繁体   English

如何判断HTML5音频元素是否正在播放Javascript

[英]How can I tell if an HTML5 Audio element is playing with Javascript

I have an audio element in a webpage, and I want to ensure that a user is not still playing it when they leave the page. 我在网页中有一个audio元素,我想确保用户在离开页面时仍然没有播放它。 How can I be sure the audio element is not playing when the page is unloaded? 如何在卸载页面时确保audio元素没有播放? So far, I have the following code, but it doesn't seem to work; 到目前为止,我有以下代码,但它似乎不起作用; the dialog that pops up upon unload reports that playing is false even when the audio is playing: 卸载报告时弹出的对话框,即使正在播放音频, playing也是false

<!DOCTYPE HTML><html>
<head>
    <script><!-- Loading Scripts -->
    function unloadTasks(){
        if (playing && !window.confirm("A podcast is playing, and navigating away from this page will stop that. Are you sure you want to go?"))
            window.alert("Here is where I will stop the page from unloading... somehow");
    }
    </script>
    <script><!-- Player Scripts -->
    var playing = false;
    function logPlay(){
        playing = isPlaying("e1audPlayer");
    }
    function isPlaying(player){
        return document.getElementById(player).currentTime > 0 && !document.getElementById(player).paused &&  !document.getElementById(player).ended;
    }
    </script>
</head>
<body onunload="unloadTasks()">
<audio id="e1audPlayer" style="width:100%;" controls="controls" preload="auto" onplaying="logPlay()" onpause="logPlay()">
    <source src="http://s.supuhstar.operaunite.com/s/content/pod/ADHD Episode 001.mp3" type="audio/mpeg"/>
    <source src="http://s.supuhstar.operaunite.com/s/content/pod/ADHD Episode 001.ogg" type="audio/ogg"/>
    Your browser does not support embedded audio players. Try <a href="http://opera.com/">Opera</a> or <a href="http://chrome.com/">Chrome</a>
</audio>
</body>
</html>

Working example 工作实例

function isPlaying(playerId) {
    var player = document.getElementById(playerId);
    return !player.paused && !player.ended && 0 < player.currentTime;
}

I believe the browser stops the audio as part of the page unload process. 我相信浏览器会在页面卸载过程中停止音频。 Hence, by the time your custom unload function is called, the audio has been stopped. 因此,在调用自定义卸载功能时,音频已停止。

You could use onbeforeunload instead of onunload - that might work (untested). 您可以使用onbeforeunload而不是onunload - 这可能有效(未经测试)。

Alternatively, you could set a flag when the audio starts, and use the onended event to change that flag when the audio ends, or when the user manually stops or pauses it. 或者,您可以在音频启动时设置标志,并在音频结束时或用户手动停止或暂停时使用onended事件更改该标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM