JavaScript / HTML - warning window appears before sound?

Code:

x = new Audio("bar.wav") x.play() alert("foo") 

Why does a warning window appear and then sound is played?

+4
source share
4 answers

This is because the sound file is loaded asynchronously by JavaScript, and then the code continues to execute. A warning is triggered first because it takes some time to load an audio file.

To fix this, you need to add an event listener at boot, for example:

 x.addEventListener('load', function() { x.play(); alert("foo"); }); 

Or you can add an event listener to the onplay event, for example:

 x.onplay = function () { alert("foo"); }; x.play(); 
+3
source

You must wait for the game event. That is when the sound begins to play. But just a tip that warns the boxes, pauses code execution and can really ruin the sound.

 x = new Audio("bar.wav") x.onplaying = function () { alert("foo"); } x.play(); 
+1
source

EDIT: this post uses the onloadeddata event, its more intesting than the example below, but I have not tested it: HTML5 Audio events not triggering in Chrome

-

Since you cannot assign an onload , you must do this:

 $(function(){ youraudioelement = new Audio("bar.wav") var audioReady = function(){ if (youraudioelement.attr('readyState')) { alert("foo"); } else { setTimeout(audioReady, 250); } } audioReady(); } 

HTML5 Audio onLoad

0
source

Just use:

 x.onended = function () { alert("foo"); }; x.play(); 
0
source

All Articles