有没有办法在页面上使用两个HTML5视频标签并保持视频同步?这意味着如果第一个视频是15.2秒,那么第二个视频是15.2秒?
我环顾四周找到了SMIL,但它看起来只适用于IE浏览器.我还试图用jQuery和jMediaElement实现我自己的东西,但似乎有很多情况下视频可能会失去同步.
以前做过吗?
html5demos 上提供的演示可以工作,但很容易不同步。
这里有一篇文章提供了一个利用 requestAnimationFrame 的解决方案(有关它的信息:Leaner, Meaner, Faster Animations with requestAnimationFrame , Animating with javascript: from setInterval to requestAnimationFrame)并且它更好:HTML5 Video: Synchronizing Playback of Two Videos。
请注意,那里提供的演示(托管在 jsfiddle)在 js 源上有错误的链接。我在这个新页面上更新了它:
请记住浏览器支持,Firefox、Chrome、Safari 6 和 IE 10 支持此功能(更多详细信息请参阅表格)。否则它会回退到 setInterval,但不会提供相同的性能和节省电池的优势。
(顺便说一句,它使用Popcorn.js ,这是 Mozilla 的一个非常好的项目)
这是代码(直接取自演示):
var videos = {
a: Popcorn("#a"),
b: Popcorn("#b"),
},
scrub = $("#scrub"),
loadCount = 0,
events = "play pause timeupdate seeking".split(/\s+/g);
// iterate both media sources
Popcorn.forEach( videos, function( media, type ) {
// when each is ready...
media.listen( "canplayall", function() {
// trigger a custom "sync" event
this.trigger("sync");
// set the max value of the "scrubber"
scrub.attr("max", this.duration() );
// Listen for the custom sync event...
}).listen( "sync", function() {
// Once both items are loaded, sync events
if ( ++loadCount == 2 ) {
// Iterate all events and trigger them on the video B
// whenever they occur on the video A
events.forEach(function( event ) {
videos.a.listen( event, function() {
// Avoid overkill events, trigger timeupdate manually
if ( event === "timeupdate" ) {
if ( !this.media.paused ) {
return;
}
videos.b.trigger( "timeupdate" );
// update scrubber
scrub.val( this.currentTime() );
return;
}
if ( event === "seeking" ) {
videos.b.currentTime( this.currentTime() );
}
if ( event === "play" || event === "pause" ) {
videos.b[ event ]();
}
});
});
}
});
});
scrub.bind("change", function() {
var val = this.value;
videos.a.currentTime( val );
videos.b.currentTime( val );
});
// With requestAnimationFrame, we can ensure that as
// frequently as the browser would allow,
// the video is resync'ed.
function sync() {
videos.b.currentTime(
videos.a.currentTime()
);
requestAnimFrame( sync );
}
sync();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6455 次 |
| 最近记录: |