等到加载HTML5视频 [英] Wait until an HTML5 video loads

查看:86
本文介绍了等到加载HTML5视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视频标签,我动态更改其来源,因为我让用户从数据库中的多个视频中进行选择。问题是,当我改变src属性时,即使我告诉它视频也不加载。



这是我的代码:

  $(#video)。attr('src','my_video _'+ value +'。ogg'); 
$(#video)。load();
while($(#video)。readyState!== 4){
console.log(Video is not ready);
};

代码仍然处于无限循环中。



任何帮助?

编辑

/ p>

  //在已加载的元数据上添加一个侦听器
v.addEventListener('loadeddata',function(){
console.log(Loaded the video's data!);
console.log(Video Source:+ $('#video')。attr('src'));
console。 log(Video Duration:+ $('#video')。duration);
},false);

好的这是我现在的代码。源打印效果很好,但我仍然无法获得持续时间:/ b> 解决方案

您并不需要jQuery因为有一个媒体API 可以为您提供所有您需要的功能。

  var video = document.getElementById('myVideo'); 
video.src ='my_video_'+ value +'.ogg';
video.load();

媒体API还包含 load() 方法:使元素重置并开始从头开始选择和加载新的媒体资源。



(Ogg不是最好的格式,因为它是仅支持有限数量的浏览器。我建议使用WebM和MP4覆盖所有主流浏览器 - 您可以使用 canPlayType() 函数决定要播放哪一个)。



然后你可以等待 loadedmetadata loadeddata (取决于您想要的)事件触发:

  video.addEventListener('loadeddata',function(){
//视频被加载并且可以播放
},false);


I have a video tag, that I dynamically change its source as I am letting the user to choose from a number of videos from the database. The problem is that when I change the src attribute the video doesn't load even if I tell it to.

Here is my code:

$("#video").attr('src', 'my_video_'+value+'.ogg');
$("#video").load();
while($("#video").readyState !== 4) {
        console.log("Video is not ready");
};

The code still stays in a infinite loop.

Any help?

EDIT:

To Ian Devlin:

//add an listener on loaded metadata
v.addEventListener('loadeddata', function() {
    console.log("Loaded the video's data!");
    console.log("Video Source: "+ $('#video').attr('src'));
    console.log("Video Duration: "+ $('#video').duration);
}, false);

Ok this is the code I have now. The source prints great, but I still can't get the duration :/

解决方案

You don't really need jQuery for this as there is a Media API that provides you with all you need.

var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();

The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."

(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType() function to decide on which one to play).

You can then wait for either the loadedmetadata or loadeddata (depending on what you want) events to fire:

video.addEventListener('loadeddata', function() {
   // Video is loaded and can be played
}, false);

这篇关于等到加载HTML5视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆