简体   繁体   English

检查声音文件是否存在javascript

[英]Check if sound file exists javascript

I have an HTML5 file, with javascript to load sounds. 我有一个HTML5文件,可使用javascript加载声音。 The sound could either be in one of the two locations: 声音可能在两个位置之一中:

../../Apps/ app name /sounds ../../Apps/应用名称/ sounds
or 要么
../../Shared/Sounds ../../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. 应该发生的是,当调用函数getSound时,它首先检查声音的第一个位置,如果该文件不存在,则转到第二个。 I've tried a couple of things before but none worked. 我之前尝试过几件事,但没有任何效果。

NB Variable blink stores string "../../Apps/ app name " 注意:变量blink存储字符串“ ../../Apps/应用名称

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. 这是行不通的,因为在开始播放之前,持续时间显然一直为NaN,因此isNan函数始终返回true。

I've also tried a fileExists function I found online: 我还尝试了在网上找到的fileExists函数:

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. 所以我要问的是,有没有一种方法可以使用javascript检查声音文件是否存在,或者是否可以检查声音文件是否实际加载到了所使用的变量中。

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. 因此,如果浏览器找到了源,则它将返回true和false。 The duration value will always be present for a valid audio or video object. 有效音频或视频对象的持续时间值将始终存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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