HTML 5视频。使用源元素而不是attr返回播放错误

时间:2013-04-09 09:39:17

标签: javascript html5 video error-handling

我希望为简单的HTML5视频元素添加一些错误处理。 我使用这个代码块online

JS

function playbackFailed(e) {
   // video playback failed - show a message saying why
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('You aborted the video playback.');
       break;
    case e.target.error.MEDIA_ERR_NETWORK:
      alert('A network error caused the video download to fail part-way.');
      break;
   case e.target.error.MEDIA_ERR_DECODE:
      alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
      break;
   case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
     alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');
     break;
   default:
     alert('An unknown error occurred.');
     break;
   }
}

HTML

<video id="a" src="tgif.vid" autoplay controls onerror="playbackFailed(event)" poster="http://img.rasset.ie/000736d2-512.jpg" width="620" height="400"></video>

以上工作正常,当页面加载时我会收到一个活泼的警告框。

但是如果我没有“src”属性而是使用<source>元素中的<video>标签“onerror(event)”不会触发?示例标记:

<video id="b" autoplay controls onerror="playbackFailed(event)" poster="http://img.rasset.ie/000736d2-512.jpg" width="620" height="400">
    <source src="tgif.vid">
</video>

注意我已经在ids“a”和“b”之上给出了两个视频元素。

有人可以在下面的代码中解释原因:

<script>
var a = document.getElementById('a');
var b = document.getElementById('b');

a.addEventListener('error', function(e){alert('error event on a')});
b.addEventListener('error', function(e){alert('error event on b')});

</script>

我只收到“a”而不是“b”的警告

我需要使用<source>标记,因为我将为不同的设备提供多种媒体类型等。

提前感谢您的任何答案/评论

取值

1 个答案:

答案 0 :(得分:9)

如果涉及来源,errors in loading sources must be caught from the <source> elements本身。但是,要检查所有<source>元素是否都失败,check the <video> element's networkState property如果它是NETWORK_NO_SOURCE

有关以下内容的更多详情:

Here's a sample code当第一个源无法加载并将错误输出到控制台时:

HTML

<video id="b" autoplay controls poster="http://img.rasset.ie/000736d2-512.jpg" width="620" height="400">
    <source src="tgif.vid" />
    <source src="http://html5doctor.com/demos/video-canvas-magic/video.mp4" />
    <source src="http://html5doctor.com/demos/video-canvas-magic/video.webm" />
    <source src="http://html5doctor.com/demos/video-canvas-magic/video.ogg" />
</video>

JS(使用处理程序来避免inine脚本)

var sources = document.getElementsByTagName('source'),
    i;

for (i = 0; i < sources.length; i++) {
    (function (i) {
        sources[i].addEventListener('error', function (e) {
            console.log('Error loading: '+e.target.src);
        });
    }(i));
}