Rob Rob - 6 months ago 14
Javascript Question

Grab n-th frame from video for preview

If I have a video file in a javascript document, how do I grab a frame from the middle? This grabs the current frame, but I want a frame from the middle for a thumbnail. Is this something that can be easily done? This kind of works, but I'm not able to set the frame back to the beginning after the grab is finished.

http://jsbin.com/betibe

var v = document.getElementById('v');
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');

var cw = canvas.width;
var ch = canvas.height;

draw(v,context,cw,ch);
v.currentTime = 5;

function draw(v,c,w,h) {
c.drawImage(v,0,0,w,h);
setTimeout(draw,20,v,c,w,h);
}

Answer

I apologize for the previous answer,

video.seekTo({ frame: frameNum });

did the trick for me. Customize the frameNum however you want.

Demo

HTML:

  <div class="frame">  
  <span id="currentFrame">0</span>
  </div>

<video height="180" width="100%" id="video"> 
  <source src="http://www.w3schools.com/html/mov_bbb.mp4"></source>
</video>

<div id="controls">
  <button id="play-pause">Play</button>
</div>

JS:

var currentFrame = $('#currentFrame');
var frameNum =100;

var video = VideoFrame({
    id : 'video',
    frameRate: 29.97,
    callback : function(frame) {
        currentFrame.html(frame);
    }
});

video.seekTo({ frame: frameNum });


$('#play-pause').click(function(){
    if(video.video.paused){
        video.video.play();
        video.listen('frame');
        $(this).html('Pause');
    }else{
        video.video.pause();
        video.stopListen();
        $(this).html('Play');
    }
});

For reference on the videoframe visit: https://github.com/allensarkisyan/VideoFrame

Comments