I have an HTML5 file, with javascript to load sounds. The sound could either be in one of the two locations:
../../Apps/ app name /sounds
or
../../Shared/Sounds
What is supposed to happen is that when the function getSound is called, it first checks the first location for the sound, and if the file doesn't exist there, it goes to the second. I've tried a couple of things before but none worked.
N.B Variable blink stores string "../../Apps/ app name "
function getSound(s){
var url = blink + "sounds/" + s;
var testSound = new Audio(url);
if ( isNan(testSound.duration) ){
url = "../../Shared/Sounds";
}
return new Audio(url);
};
This doesn't work since apparently the duration remains NaN until after it starts playing, so the isNan function always returns true.
I've also tried a fileExists function I found online:
function fileExists(url){
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
So all I'm asking is, is there a way to check if a sound file exists using javascript, or if you can check if a sound file was actually loaded to the variable you're using.
Use
var sound = new Audio("sample_src");
if(isNaN(sound.duration)) alert("Do something");
Edit: It works after play audio. Better option:
var sound = new Audio("sample_src");
$(sound).on("canplay",function(){
//Do something if works
});
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