我想每5秒从视频中捕获一帧。
这是我的JavaScript代码:
video.addEventListener('loadeddata', function() {
var duration = video.duration;
var i = 0;
var interval = setInterval(function() {
video.currentTime = i;
generateThumbnail(i);
i = i+5;
if (i > duration) clearInterval(interval);
}, 300);
});
function generateThumbnail(i) {
//generate thumbnail URL data
var context = thecanvas.getContext('2d');
context.drawImage(video, 0, 0, 220, 150);
var dataURL = thecanvas.toDataURL();
//create img
var img = document.createElement('img');
img.setAttribute('src', dataURL);
//append img in container div
document.getElementById('thumbnailContainer').appendChild(img);
}
我的问题是,第一次生成的两个图像是相同的,而持续时间为5秒的图像却没有生成。我发现缩略图是在< video>
标记中显示特定时间的视频帧之前生成的。
例如,当时video.currentTime = 5
,生成帧0s的图像。然后视频帧跳到时间5s。因此,当时video.currentTime = 10
,将生成帧5s的图像。
问题在于(通过设置currentTime
)查找视频是异步的。
您需要收听seeked
事件,否则可能会冒实际的当前帧的风险,这很可能是您的旧值。
由于它是异步的,因此您也不能使用,setInterval()
因为它也是异步的,并且当寻求下一帧时,您将无法正确同步。无需使用,setInterval()
因为我们将利用seeked
事件来代替,这将使所有内容保持同步。
通过稍微重写代码,您可以使用该seeked
事件来遍历视频以捕获正确的帧,因为此事件可确保我们实际上位于通过设置该currentTime
属性所请求的帧。
例
// global or parent scope of handlers
var video = document.getElementById("video"); // added for clarity: this is needed
var i = 0;
video.addEventListener('loadeddata', function() {
this.currentTime = i;
});
将此事件处理程序添加到聚会中:
video.addEventListener('seeked', function() {
// now video has seeked and current frames will show
// at the time as we expect
generateThumbnail(i);
// when frame is captured increase, here by 5 seconds
i += 5;
// if we are not passed end, seek to next interval
if (i <= this.duration) {
// this will trigger another seeked event
this.currentTime = i;
}
else {
// Done!, next action
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句