Javascript alert box blocks sound object

198 Views Asked by At

I have a small problem. Basically, I am trying to make an application that it will pop up a box while playing a certain sound. Here is the fault part of the code:

    var audio = new Audio('song.mp3');
    audio.play();
    alert(1);

The problem is that the audio plays after the alert box. I guess this happens because the application doesn't load the song file immediately but I have now idea how can I make it?

1

There are 1 best solutions below

0
On BEST ANSWER

The canplay event occurs when the browser can start playing the specified audio/video (when it has buffered enough to begin).

So try this:

var audio = new Audio('song.mp3');
    audio.oncanplay  = function() {
        audio.play();
        alert("1");
    };