Firefox 不会在标签上触发错误事件<audio>或显示回退文本



我使用<audio>标记在许多浏览器中播放音频文件。

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还承诺,如果<audio><video>标签无法播放媒体,则会发送error事件。此外,它还将逐一检查嵌套在媒体标签中的标签(<source>或其他标签,最后一个可能是错误消息),直到找到一个可以使用的标签。这些似乎都不适合我;不会在元素上触发错误事件,也不会显示错误消息。我做错了什么?

我找到的解决方法是:

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上,错误事件不会触发,您必须依赖<audio>元素的networkState标志,将其与NETWORK_NO_SOURCE进行比较。您不能在设置<source>元素的src属性后立即检查它,因为在IE networkState === NETWORK_NO_SOURCE上,直到浏览器真正开始下载文件。因此,在检查标志值之前,请设置大约3秒的超时(这不是一门精确的科学),这样很有可能给IE足够的时间来确定它是否能够播放文件。

更新

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

相关内容

最新更新