Loading audio (or video, or images) is an asynchronous operation so you need to listen to tap into the browser's callback mechanism to know when the file is ready for use.
Update
Added type
to the mix, and demo:
In case of audio (and video) you can listen to the canplay
event:
function playit() {
var audio = new Audio();
audio.addEventListener('canplay', function() {
this.play();
}, false);
audio.type = 'audio/mpeg';
audio.src = '...';
}
You could also use canplaythrough
instead of canplay
.
Optionally do this:
function playit() {
var audio = new Audio();
audio.preload = 'auto';
audio.autoplay = true;
audio.type = 'audio/mpeg';
audio.src = '...';
}
There seem to be an issue with Chrome though - it cancels flat out: