【问题标题】:Firefox doesn't fire error event on <audio> tag or display fallback textFirefox 不会在 <audio> 标记上触发错误事件或显示后备文本
【发布时间】:2012-10-05 04:34:21
【问题描述】:

我正在使用&lt;audio&gt; 标签在多个浏览器中播放音频文件。

var audioTag = document.createElement("audio"),
    sourceTag = document.createElement("source"),
    sorryTag = document.createElement("div");
sorryTag.innerHTML = "This filetype not supported";
audioTag.onerror = function() {
    //some error handling code
}
sourceTag.onerror = function() {

    /some error handling code
}
sourceTag.src = "myfile.mp3";
audioTag.appendChild(sourceTag);
audioTag.appendChild(sorryTag);
//add audioTag to DOM

这导致

<audio>
    <source src='myfile.mp3' />
    <div>This filetype not supported</div>
</audio>

Firefox 不能播放 MP3 文件,我可以接受。 Mozilla also promises 表示,如果 &lt;audio&gt;&lt;video&gt; 标签无法播放媒体,将调度 error 事件。它还将逐个检查嵌套在媒体标签中的标签(&lt;source&gt; 或其他标签,最后一个可能是错误消息),直到找到可以使用的标签。这些似乎都不适合我;元素上永远不会触发错误事件,也不会显示错误消息。我做错了什么?

【问题讨论】:

  • 如果你使用
  • 不可能。我在设置source 标记的src 属性之前添加了onerror 事件侦听器。更新代码以反映这一点。
  • 对于video标签,该事件在其他浏览器上触发得很好,只是在audio标签的FF上没有
  • 嗯。这很奇怪。是否可以发布指向显示问题的页面的链接?
  • 很遗憾没有。这是一项工作,目前正在开发中。我找到了一种解决方法(基于在超时后检查音频元素的 networkState 属性),一旦我验证它工作正常,我将在下面发布。

标签: firefox cross-browser html5-audio


【解决方案1】:

我找到的解决方法是:

var audioTag = document.createElement("audio"),
    sourceTag = document.createElement("source");

//Add error event listeners for browsers other than FF
audioTag.onerror = function() {
    console.log("file can't be played. error from audio tag");
}
sourceTag.onerror = function() {
    console.log("file can't be played. error from source tag");
}
//The only way to tell that file failed to play on FF
//Timeout is because audioTag.networkState === audioTag.NETWORK_NO_SOURCE
//on IE till it starts downloading the file
setTimeout(function() {
    if(audioTag.networkState === audioTag.NETWORK_NO_SOURCE) {
        console.log("this hack is only for <audio> on FF.");
        console.log("Not for <video> and on no other browsers");
    }
}, 3000);
sourceTag.src = "<file_url>";
audioTag.appendChild(sourceTag);

基本上,创建媒体和源标签,添加错误处理程序,然后将源标签附加到媒体标签,如果错误事件触发,那么您知道文件无法播放。

在 FF 上,错误事件不会触发,您必须依赖 &lt;audio&gt; 元素的 networkState 标志,将其与 NETWORK_NO_SOURCE 进行比较。在设置 &lt;source&gt; 元素的 src 属性后,您无法立即检查它,因为在 IE 上 networkState === NETWORK_NO_SOURCE 直到浏览器实际开始下载文件。出于这个原因,在检查标志值之前设置一个大约 3 秒的超时时间(这不是一门精确的科学),你很有可能会给 IE 足够的时间来确定它是否能够播放文件。

更新

为此编写了一个测试用例:http://jogjayr.github.com/FF-Audio-Test-Case/ 但错误事件在那里触发 OK。猜我错了;或者它在 FF14(我当时正在使用)上被破坏,因为错误事件也在我的应用程序中触发 OK。谢谢@BorisZbarsky

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    相关资源
    最近更新 更多