视频源格式无效问题



如何针对无效的.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>

为什么不工作?因为您将事件侦听器添加到div而不是视频标签的来源

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

你可以使用 canPlayType():

可能的返回值为:

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

如果,相反,您需要错误才能获得

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

您的代码必须更改为:

$('#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>

最新更新