视频源无效格式问题

时间:2018-03-01 20:04:12

标签: javascript jquery

如何针对无效的.mp4格式文件进行测试以隐藏相应的容器?

<div id="video">
    <video controls width="320" height="240">
        <source src="<?php echo $row["username"]);?>" type="video/mp4">
    </video>
</div>


这是我的尝试:

<script>
    document._video = document.getElementById("video");

    document._video.addEventListener('error',function(){
        video.style.display = "none";
     });
</script>

2 个答案:

答案 0 :(得分:1)

为什么不工作?因为你addeventlistener不是视频标签的来源

<div id="video">
      <video controls="controls" width="320" height="240">
          <source src="aaaa" type="video/mp4"/>
      </video>
  </div>

<script>
    var v = document.querySelector('#video');
    var sources = v.querySelectorAll('source');

    if (sources.length !== 0) {
        var lastSource = sources[sources.length-1];

        lastSource.addEventListener('error', function() {
            v.style.display="none";
        });
    }
    </script>

答案 1 :(得分:0)

您可以使用canPlayType()

可能的返回值是:

  • 可能:指定的媒体类型似乎可播放。
  • 可能:无法判断媒体类型是否可播放。
  • ''(空字符串):无法播放指定的媒体类型。

如果您需要onerror才能获得

  

....在尝试加载或执行媒体时发生某种形式的错误时会发生这些事件。

您的代码必须更改为:

$('#video source').on('error',function(e) {

摘录:

var result = $('#video video').get(0).canPlayType($('#video video source').attr('type'));

console.log('The first video can be played: ' + result);

$('#video source').on('error',function(e) {
    //
    // this in order to dectect wrong sources
    //
    $('#video').toggle();
    console.log('The first video source has errors...');
});

$('#newvideo source').on('error',function(e) {
    //
    // this in order to dectect wrong sources
    //
    $('#newvideo').toggle();
    console.log('The second video source has errors...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="video">
    <p>The first video: it's ok</p>
    <video controls width="320" height="240">
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
    </video>
</div>

<!-- This second video has an invalid source -->
<div id="newvideo">
    <p>The second video: it has an invalid source</p>
    <video controls width="320" height="240">
        <source src="aaaaaa" type="video/mp4">
    </video>
</div>