我想每 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>
tag.
例如,当video.currentTime = 5
,生成第0帧的图像。然后视频帧跳转到时间5s。所以当video.currentTime = 10
,生成第5s帧的图像。
Cause
问题是寻找视频(通过设置它currentTime
) 是异步的。
你需要听seeked事件,否则它将冒着采用实际当前帧的风险,这可能是您的旧值。
因为它是异步的,所以你必须not使用setInterval()
因为它也是异步的,当寻找下一帧时您将无法正确同步。没有必要使用setInterval()
因为我们将利用seeked
相反,事件将使一切保持同步。
Solution
通过稍微重写代码,您可以使用seeked
事件来浏览视频以捕获正确的帧,因为此事件通过设置来确保我们实际上处于我们请求的帧currentTime
财产。
Example
// 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 past end, seek to next interval
if (i <= this.duration) {
// this will trigger another seeked event
this.currentTime = i;
}
else {
// Done!, next action
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)