Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay in JavaScript audio playback

I am writing a very simple game in JavaScript and I notice that there is about a 0.5 seconds delay from the time that I call the "play" function to the time the audio starts playing. Is this normal?

This is the code I have:

var audio = new Audio("games/aventura4/sfx/hit.wav");
audio.play();

I have also tried initializing the audio variable only once, and then just calling audio.play() (after doing audio.currentTime = 0, of course), and the delay is still there!

Am I doing anything wrong? (I'm trying this on Safari, btw).

Edit: after experimenting with this, it seems that the problem is just running this on Safari. There is no delay on Chrome. But that still leaves the question of why does it happen in Safari?!?!

Edit 2: it seems it might be related to this other question: HTML5 Audio tag on Safari has a delay

like image 616
santi.ontanon Avatar asked Sep 08 '26 00:09

santi.ontanon


1 Answers

When you hit the "Play" button (whether you do it manually or in code) a network request is issued to obtain the audio. While it can start before the full file is downloaded, it needs to download a reasonable amount into the buffer before it can start - otherwise it would stutter badly as it tried to play.

You can hint to the browser that you would like the audio pre-loaded with:

<audio preload="auto"> 

But that is simply a hint, it won't guarantee anything. If you use this attribute too liberally it may be counter-productive.

With your JavaScript solution, you could instantiate the audio earlier. There is an oncanplaythrough event that fires when it has buffered enough to play.

like image 88
Fenton Avatar answered Sep 10 '26 14:09

Fenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!