Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preload a sound in Javascript?

I can preload images easily thanks to the onload function. But it doesn't work with audio. Browsers like Chrome, Safari, Firefox, etc. don't support the onload functions in the audio tag.

How do I preload a sound in Javascript without using JS libraries and without using or creating HTML tags?

like image 399
Manuel Ignacio López Quintero Avatar asked Mar 15 '11 15:03

Manuel Ignacio López Quintero


People also ask

How do I preload audio?

We use preload=”auto” attribute to preload the audio file. The HTML Audio Preload Attribute is used to specify how the author thinks the audio should be loaded when the page loads. The audio preload attribute allows the author to indicate to the browser how the user experience of a website should be implemented.

What is use of preload auto attribute in audio tag?

The preload attribute specifies if and how the author thinks that the audio file should be loaded when the page loads. The preload attribute allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience. This attribute may be ignored in some instances.

Can JavaScript play WAV files?

Method 2: JavaScriptYou may also load a sound file with JavaScript, with new Audio() . const audio = new Audio("freejazz. wav"); You may then play back the sound with the .

How do I embed a sound in HTML?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash. After the release of HTML5, it is possible.


1 Answers

Your problem is that Audio objects don't support the 'load' event.

Instead, there's an event called 'canplaythrough' that doesn't mean it's fully loaded, but enough of it is loaded that at the current download rate, it will finish by the time the track has had enough time to play through.

So instead of

audio.onload = isAppLoaded; 

try

audio.oncanplaythrough = isAppLoaded; 

Or better yet.. ;)

audio.addEventListener('canplaythrough', isAppLoaded, false); 
like image 92
McKayla Avatar answered Sep 28 '22 02:09

McKayla