Ad

Can't Avoid Delay In Javascript Audio

- 1 answer

I wonder whether this is an unresolved issue or not.

OK, so I have this very simple test code:

var audio = new Audio("0.mp3");
audio.oncanplay = function() {
    audio.play();
    setTimeout(function() {
        audio.pause();
    }, 30);
}

What I intend to do is to play my sound for a very short period of time.
I know for sure that the audio (a middle-C note) starts in 0:00:00.
Note that I use the oncanplay event to make sure the audio is loaded when I try to play it.

The problem I have is that I get unpredictable results. Sometimes (most of the times, really), audio is not heard at all. Other times, audio is heard but not always for the same period of time.

I know that Javascript can be slow, but I wonder, for example in the first case, why is the timeout set at all if the audio isn't playing yet.

Is this a known issue? It is possible to have a better control over Audio?

-Thanks

Ad

Answer

Avoid using setTimeout, which is not accurate and may result (as in your case) in a race condition. Use the 'timeupdate' event to keep track of the progress. Here the song will play and auto-pause after 7 seconds:

var audio = new Audio("0.mp3");
audio.oncanplay = function() {

  audio.play();
  audio.addEventListener('timeupdate', function() {
    console.log(audio.currentTime.toFixed());
    if ( audio.currentTime >= 7 ) audio.pause();
  });

} 

JSFiddle Demo

Ad
source: stackoverflow.com
Ad