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?
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.
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.
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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With