PDA

View Full Version : Execute function when play button is clicked in html5 audio player



windbrand
03-03-2013, 12:29 AM
Is it possible to detect when the play button in the html5 audio player is clicked? For example:


<audio controls>
<source src="music.mp3"/>
<source src="music.ogg" />
</audio>
....
....
$('playbutton').on('click', function(e){
//some functions
});

jscheuer1
03-03-2013, 08:59 AM
You can use jQuery to get the element, but there's no direct interface with the play button in jQuery. You could use something like:

http://www.jplayer.org/

With its API you could detect play.

However, since (in browsers that support HTML 5 audio) the play event is the one almost universally supported event in ordinary javascript, rather than get into a complex API, you can just do:


<!DOCTYPE html>
<html>
<head>
<title>Detect Audio Play - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<audio controls id="myaudio">
<source src="music.ogg" type="audio/ogg">
<source src="music.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script type="text/javascript">
if (window.addEventListener){
(function(){
function playfunc(){alert('Play Was Pressed');}
document.getElementById('myaudio').addEventListener('play', playfunc, false);
})();
}
</script>
</body>
</html>