HTML 5视频.返回源元素而不是attr的播放错误

HTML 5 Video. Returning playback error with source element instead of attr

本文关键字:attr 播放 错误 视频 返回 元素 HTML      更新时间:2023-09-26

我希望添加一些错误处理到一个简单的HTML5视频元素。我使用的这段代码在网上随处可见:

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;
   }
}

<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(事件)"不火?示例标记:

<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>

注意,我在id为"a"answers"b"的上方给了两个video元素。

谁能解释一下为什么在下面的代码:

<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>标签,因为我将为不同的设备等提供多种媒体类型。

提前感谢任何回答/评论

S

如果涉及源,则必须从<source>元素本身捕获加载源的错误。然而,要检查是否所有<source>元素都失败了,检查<video>元素的networkState属性是否为NETWORK_NO_SOURCE

更多的细节在这里:

  • HTMLMediaElement
  • <source>
  • 使用HTML5音频和视频

下面是第一个源加载失败并向控制台输出错误的示例代码:

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(使用处理程序来避免使用内嵌脚本)

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));
}