Reputation: 91
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.
Upvotes: 3
Views: 6456
Reputation: 171
use this function, then call it in code:
doesFileExist(path: string) {
let xhr = new XMLHttpRequest();
xhr.open('HEAD', path, false);
xhr.send();
if (xhr.status == 404) {
return false;
} else {
return true;
}
}
Upvotes: -1
Reputation: 61
What you say is complicated in my opinion. When the audio object loads a file, when it is not found the browser causes an error. When you want to check if an audio object exists just check the file time returned by the server to the browser.
Here is the correct function ...
function audiovideoExist(ObjectAV){
var exist = (Number.isFinite(ObjectAV.duration))? true: false;
return exist;
}
So if the browser found a source it returns true and false otherwise. The duration value will always be present for a valid audio or video object.
Upvotes: -1
Reputation: 51
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
});
Upvotes: 3
Reputation: 207501
If the file does not exist, the error event will fire
mySound = new Audio();
mySound.onerror = function(){ alert("error");};
mySound.src = "xxxx";
Problem is this is not synchronous.
Upvotes: 0