I am trying to create a cross device / browser scheme and a preload scheme for the GameAPI that I am working on. The sound file will be preloaded and will issue a callback after it is completed.
The problem is that the sound will not start loading during slow page loads, but will usually work in the second attempt, probably because it cached it and knows that it exists.
I narrowed it down to the function audio.load (). Getting rid of it solves the problem, but, interestingly, my droid motorola needs this feature.
What are some experiences with HTML5 audio preloading?
Here is my code. Yes, I know that loading images in a separate function can lead to a race condition :)
var resourcesLoading = 0; function loadImage(imgSrc) { //alert("Starting to load an image"); resourcesLoading++; var image = new Image(); image.src = imgSrc; image.onload = function() { //CODE GOES HERE //alert("A image has been loaded"); resourcesLoading--; onResourceLoad(); } } function loadSound(soundSrc) { //alert("Starting to load a sound"); resourcesLoading++; var loaded = false; //var soundFile = document.createElement("audio"); var soundFile = document.createElement("audio"); console.log(soundFile); soundFile.autoplay = false; soundFile.preload = false; var src = document.createElement("source"); src.src = soundSrc + ".mp3"; soundFile.appendChild(src); function onLoad() { loaded = true; soundFile.removeEventListener("canplaythrough", onLoad, true); soundFile.removeEventListener("error", onError, true); //CODE GOES HERE //alert("A sound has been loaded"); resourcesLoading--; onResourceLoad(); } //Attempt to reload the resource 5 times var retrys = 4; function onError(e) { retrys--; if(retrys > 0) { soundFile.load(); } else { loaded = true; soundFile.removeEventListener("canplaythrough", onLoad, true); soundFile.removeEventListener("error", onError, true); alert("A sound has failed to loaded"); resourcesLoading--; onResourceLoad(); } } soundFile.addEventListener("canplaythrough", onLoad, true); soundFile.addEventListener("error", onError, true); } function onResourceLoad() { if(resourcesLoading == 0) onLoaded(); }
It is difficult to diagnose a problem because it shows no errors and ends from time to time.
source share