Detect a remote file error(404) using html5 audio api
http://days4god.com/playergenerator.html
That’s a script I made however, it stops executing when an error occurs, I’d like to detect the 404 error and proceed onto the next file.
if(audio.error != null) {
if (audio.error.code == 4) {
console.log(“File not found.”);
}
}
This appears to not function/work.
How is the audio file being loaded? Is there a way you could share the code?
I create a html element and then append it and using the html5 media api, I try to get the status of the file.
function appendAudio(n) {
progress += 1; //7
updateProgressBar();
if(n != tracks) { // recursive loop
console.log("Appending track,\n", (n+1) ,": ", titles[n]);
var audio = document.createElement("audio");
audio.src = links[n]; // Assign attribute values
audio.id = "audiotrack" + n;
audio.autoplay = true;
audio.muted = true;
htmlplayground.innerHTML = audio.outerHTML;
// get Duration of the track appended above
console.log("Getting duration");
getDuration(n);
} else {
console.log("Process Complete.")
checkdurationLength();
// Clean up HTML after function has done it's job
// $("#htmlplayground").html();
}
}
function getDuration(n) {
progress += 1; //8
updateProgressBar();
var audio = document.getElementById("audiotrack" + n);
audio.onerror = function() {
console.log("Error " + audio.error.code + "; details: " + audio.error.message);
}
if(audio.error == null) {
console.log("THere are no errors!");
audio.oncanplaythrough = function () {
// declare elment in a variable
var myAudio = document.getElementById("audiotrack" + n); //Object Identifier
// parse the duration and append it into the array
duration[n] = parseInt(myAudio.duration.toFixed()); // Get duration of the Track and Round it and convert it into a integer
console.log("- Duration Set.");
if(audio.error != null) {
if (audio.error.code == 4) {
console.log("File not found.");
}
}
if(duration[n] == undefined && audio.error == null) {
getDuration(n)
} else {
appendAudio(n+1);
}
}
} else {
appendAudio(n+1)
}
}
What does audio.error say? Does it return a 404 with which you can work with? If that is the case, you would have to create a fallback similar to the one you have written but the code should be 404, not just 4. Have you tried that?
I haven’t tried to use 404, but the 4 came from viewing the elements dom properties
I tried to use the XHRequest but cross-origin policy wont let me.
It’s returning a 404, so use a 404 for error handling. “Error 4 details” is something you wrote in your code, that’s not the returned value. The returned value is 404, you can see it at the end of the GET requests.
I used onplay and onerror instead of it - works perfect now - i tried readyState and logging the variable.