【问题标题】:With new Audio(), is there any way to find out of the audio file exists?使用 new Audio(),有没有办法找出音频文件是否存在?
【发布时间】:2016-05-30 16:36:13
【问题描述】:

有什么方法可以从初始化的 Audio 实例中找出音频文件是否存在?

例如,如果我尝试比较现有音频和不存在的音频文件:

new Audio('exists.mp3').readyState           => 0

new Audio('does_not_exist.mp3').readyState   => 0
(HTTP "Content-Type" of "text/html" is not supported. Load of media resource http://amc.narom.no/Steid failed.)

返回值相同,但控制台记录了无法加载媒体资源的错误。有没有办法捕捉到这个消息,或者使用 Audio 对象中的任何方法来找出音频文件是否存在?

注意: 我知道我可以向音频源发出 HttpRequest 或 AJAX 请求以检查它是否存在,但想知道这是否可以以更有效的方式完成。

【问题讨论】:

    标签: javascript audio html5-audio


    【解决方案1】:

    不是同步的,因此立即访问属性将不起作用,因为您必须等待浏览器尝试网络请求,但是是的,您可以使用 errorloadeddata 事件(可以选择将其他类似的媒体事件替换为确定成功)。

    var a = new Audio('doesitexist.mp3');
    a.onerror = function() {
        console.log('File does not exist.');
    };
    a.onloadeddata = function() {
        console.log('File exists.');
    };
    

    在至少成功加载一些数据之前,loadeddata 事件不会触发,如果请求返回无效响应(如 404 错误),error 将触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2022-06-21
      • 1970-01-01
      • 2015-02-27
      相关资源
      最近更新 更多