如何判断HTML5 Audio元素是否正在使用Javascript

前端之家收集整理的这篇文章主要介绍了如何判断HTML5 Audio元素是否正在使用Javascript前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在网页中有一个音频元素,我想确保用户在离开页面时仍然没有播放它.如何在卸载页面时确保音频元素没有播放?到目前为止,我有以下代码,但它似乎不起作用;卸载报告时弹出的对话框,即使正在播放音频,播放也是假的:
<!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;
}

猜你在找的HTML5相关文章