Firefox不会在<audio>标记上显示错误事件或显示后备文本</audio>

时间:2012-08-30 01:21:12

标签: firefox cross-browser html5-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 also promises如果error<audio>标记无法播放媒体,则会发送<video>个事件。并且它将逐个浏览嵌套在媒体标记内的标记(<source>或其他标记,最后可能是错误消息),直到找到它可以使用的标记。这些似乎都不适合我;永远不会在元素上触发错误事件,也不会显示错误消息。我做错了什么?

1 个答案:

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

<强>更新

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