How to find out if an HTML5 Audio element is playing using Javascript

I have an audio element on a web page and I want to make sure that the user is not playing it yet when he leaves the page. How can I make sure that the audio element does not play when the page is unloaded? So far I have the following code, but it does not work; the dialog box that appears when downloading reports, playing is false even when playing a sound:

 <!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

+7
source share
2 answers
 function isPlaying(playerId) { var player = document.getElementById(playerId); return !player.paused && !player.ended && 0 < player.currentTime; } 
+14
source

I believe the browser stops the sound as part of the page loading process. Therefore, by the time your custom upload function was called, the sound was stopped.

You can use onbeforeunload instead of onunload - this may work (unverified).

Alternatively, you can set a flag when the sound starts and use the onended event to change this flag when the sound ends, or when the user manually stops or pauses it.

0
source

All Articles