2

I think this code should play a sound, then show an alert box. It works with IE9, but with Chrome & Firefox, the sound is played, but the callback is never called - so no alert box.

I'm a c#, c++ programmer new to javascript, and I could use some help! Thanks.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script type="text/javascript">
        var playAll= function(){
             var audio = document.getElementById('s');

             var callback = function(e){
                alert("ended"); 
             };

            audio.onended = callback;
            audio.play();
        }

    </script>
</head>

<body>
    <input name="Button1" type="button" value="Play" onclick="playAll()"/>

    <audio ID="s">
    <source src="s.mp3"  >
    <source src="s.ogg"  >
</body>

</html>
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
jack
  • 31
  • 3

2 Answers2

4

Just to be sure that it is not an issue of invalid html, use the following valid version

<audio ID="s">
  <source src="s.mp3" />
  <source src="s.ogg" />
</audio>

and then use the correct way to bind events.

audio.addEventListener( "ended", callback, false);
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
3

onended seems to be specific to IE9, Chrome and Firefox will fire the event ended, which you can bind a function to like so: v.addEventListener("ended", function() { alert("ended"); }

Remember that the HTML5 spec is still being developed, and not all browsers implement it the same way.

There's a similar question here: HTML 5 Video OnEnded Event not Firing

Community
  • 1
  • 1
thedaian
  • 1,313
  • 9
  • 11
  • Thanks! That code works with IE & Chrome, but to get it to work with Firefox, I had to add the 'false' parameter: audio.addEventListener("ended", function(e) { alert("ended"); },false); – jack May 17 '11 at 16:14