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

Lin*_*Lin 39 javascript video html5 canvas html5-canvas

我想每隔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);
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是生成的前两个图像是相同的,并且不生成持续时间为5秒的图像.我发现缩略图是在特定时间的视频帧显示在< video>标签之前生成的.

例如,当video.currentTime = 5生成帧0的图像时.然后视频帧跳到5秒.因此,当video.currentTime = 10生成帧5s的图像时.

小智 50

原因

问题是寻找视频(通过设置它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;
});
Run Code Online (Sandbox Code Playgroud)

将此事件处理程序添加到聚会:

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
    }
});
Run Code Online (Sandbox Code Playgroud)

在这里演示

  • 我尝试使用你的代码.现在我有另一个问题.由于被搜索,当我通过点击时间线搜索视频时,也会生成图像.但我不希望这样.**编辑**我已经解决了这个问题.谢谢. (2认同)