Reputation: 963
I am wanting to know how to check if a HTML5 audio element is loaded.
Upvotes: 44
Views: 49116
Reputation: 1
Just use audio.readyState is fine:
if(audio.readyState === 4) {
console.log('Audio loaded');
} else {
console.log('Audio NOT loaded');
}
Upvotes: 0
Reputation: 21
Another option is networkState:
var myAudio = new Audio(url);
var networkState = myAudio.networkState;
networkState is a helpful companion property to the previously mentioned readyState, and can be handy in certain contexts where readyState might fall short, such as discerning whether or not a file is likely going to load at all. This can be done by checking it at set intervals.
Upvotes: 1
Reputation: 75707
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>
Upvotes: 57
Reputation: 1359
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:
Upvotes: 33