简体   繁体   中英

Check if sound file exists javascript

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.

NB 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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM