我想每 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 past end, seek to next interval
if (i <= this.duration) {
// this will trigger another seeked event
this.currentTime = i;
}
else {
// Done!, next action
}
});
关于javascript - 使用 HTML5 和 JavaScript 从视频中捕获帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175174/