I am wanting to know how to check if a HTML5 audio element is loaded.
To check if audio is playing with JavaScript, we can use the paused property of the audio element. const isPlaying = (audElem) => { return !
The HTML <audio> element is used to play an audio file on a web page.
HTML5 <audio> Tag. Since the release of HTML5, audios can be added to webpages using the “audio” tag. Previously, audios could be only played on web pages using web plugins like Flash. The “audio” tag is an inline element that is used to embed sound files into a web page.
<audio>: The Embed Audio element. The <audio> HTML element is used to embed sound content in documents.
To find out when the audio is ready to start playing, add listeners for the oncanplay
or oncanplaythrough
events. To find out when the audio has loaded at all, listen to the onloadeddata
event:
<audio oncanplay="myOnCanPlayFunction()" oncanplaythrough="myOnCanPlayThroughFunction()" onloadeddata="myOnLoadedData()" src="myaudio.ogg" controls> <a href="myaudio.ogg">Download</a> </audio> <script> function myOnCanPlayFunction() { console.log('Can play'); } function myOnCanPlayThroughFunction() { console.log('Can play through'); } function myOnLoadedData() { console.log('Loaded data'); } </script>
Check out robertc's answer for how to use event listeners. You can also directly check an audio element's ready state:
var myAudio = $('audio')[0]; var readyState = myAudio.readyState;
readyState
will be a number. From Mozilla's docs:
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