detect/handle浏览器无法播放媒体文件怎么办

How do I detect/handle a browser's failure to play a media file

我正在使用 JavaScript library 播放 mp3 文件。由于我无法控制的情况,我定期 link 到一个无法播放的文件。发生这种情况时,我在 Firebug 中看到一条消息,说明无法解码该文件。

Media resource https://example.com/bad_file.mp3 could not be decoded.


Click here to see the behavior in action on jsfiddle

因为我无法替换文件,所以我正在寻找一种方法来确定文件是否可以播放。该框架提供了一个 onerror() 脚本本身加载失败的方法,但没有提供文件无法播放的方法。

虽然可以接受特定于 SoundManager2 的答案,但我更喜欢独立于任何特定库或框架的解决方案。

如果您使用的是标准 <audio src="whatever.mp3"> 表示法,则可以使用此脚本来检测发生的任何音频错误:

function handleSourceError(e) { alert('Error loading: '+e.target.src) }
function handleMediaError(e) {
  switch (e.target.error.code) {
    case e.target.error.MEDIA_ERR_ABORTED:
      alert('You aborted the media playback.'); break;
    case e.target.error.MEDIA_ERR_NETWORK:
      alert('A network error caused the media download to fail.'); break;
    case e.target.error.MEDIA_ERR_DECODE:
      alert('The media playback was aborted due to a corruption problem or because the media used features your browser did not support.'); break;
    case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
      alert('The media could not be loaded, either because the server or network failed or because the format is not supported.'); break;
    default:
      alert('An unknown media error occurred.');
  }
}

var toArray = Array.prototype.slice;
toArray.apply(document.getElementsByTagName('audio')).forEach(function(audio){
  audio.addEventListener('error', handleMediaError);
  toArray.apply(audio.getElementsByTagName('source')).forEach(function(source){
    source.addEventListener('error', handleSourceError);
  });
});

如果您可以获得对 Audio 实例的引用,那么您可以这样添加错误处理程序:

audioInstance.addEventListener('error', handleMediaError)

一般可以给加载资源的元素添加onerror事件监听器。因此,例如,由于您正在制作音频,因此您可以将事件侦听器附加到音频元素

//assume this html:
//<audio id="myaudio" src="http://badurl.com/mp3.mp3"></audio>
document.getElementById("myaudio").addEventListener("error",function(event){
  //do error handling here
});

对于 SoundManager2 特别是你可以传入一个 onload 回调选项,它会被传递一个 success 变量,如果没有加载则为 true,如果没有加载则为 true,API reference

var mySound = soundManager.createSound({
  id: 'aSound',
  url: 'http://badurl.com/mp3.mp3',
  onload:function(success){
     if(!success){
        //error happened
     }
  } 
});
mySound.play();