首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用HTML5和JavaScript从视频中捕获帧

使用HTML5和JavaScript从视频中捕获帧
EN

Stack Overflow用户
提问于 2013-10-04 14:59:37
回答 1查看 68.9K关注 0票数 52

我想每隔5秒从视频中捕获一帧。

这是我的JavaScript代码:

代码语言: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时,将生成第0帧的图像。则视频帧跳转到时间5s。因此,当video.currentTime = 10时,将生成第5s帧的图像。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-04 15:55:54

原因

问题是寻找视频(通过设置它的currentTime)是异步的。

您需要侦听seeked事件,否则它将冒着获取实际当前帧的风险,而当前帧可能是您的旧值。

因为它是异步的,所以你必须而不是使用setInterval(),因为它也是异步的,当下一帧被搜索到时,你将不能正确地同步。不需要使用setInterval(),因为我们将使用seeked事件,它将使所有内容保持同步。

解决方案

通过稍微重写代码,您可以使用seeked事件遍历视频以捕获正确的帧,因为此事件通过设置currentTime属性确保我们实际上位于请求的帧。

示例

代码语言:javascript
复制
// 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;
});

将此事件处理程序添加到参与方:

代码语言:javascript
复制
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
  }
});
票数 62
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19175174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档