jukenduit
jukenduit

Reputation: 393

does new Audio preload the sound file?

I get an audio element and play the sound like so:

let audio = document.querySelector(`audio[data-key="${e.key}"]`);
audio.play();

However sometimes (I use Chrome) there is initially a delay when I play a sound, so I also added this code:

let audioElems = document.querySelectorAll('audio');
audioElems.forEach(function (audio) {
    new Audio(`./sounds/${audio.dataset.key}.mp3`);
});

It seemed to make a difference at first but now again sometimes I get the delay. Does the extra code make a difference, will using new Audio actually preload the sound file?

Upvotes: 1

Views: 1876

Answers (2)

frederj
frederj

Reputation: 1723

HTML5 audio/video tags have an optional preload attribute. Is this attribute currently enabled on your audio tag?

https://www.w3schools.com/tags/av_prop_preload.asp

Using the new Audio() constructor defaults to preload="auto", so that does make a difference.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement

Upvotes: 0

Kaiido
Kaiido

Reputation: 137131

It doesn't necessarily preload it, but it creates an HTMLAudioElement with the preload attribute set to auto.
This means that UAs are told that they should preload the resource if they dim it appropriate, e.g, they could ignore it if on mobile data.

console.log(new Audio)

Now to your issue, Chrome is known to not accept more than 6 simultaneous requests. So if your audioElems NodeList contains more than 6 elements, that would be the cause for some of them to be delayed until the first ones are fetched.

Also, there will always be at least a little delay, since all in MediaElement is asynchronous. Depending on what you are after, you may get better results using the Web Audio API.

Upvotes: 1

Related Questions