user2989402
user2989402

Reputation: 113

How to step one frame forward and one frame backward in video playback?

I need to search for some special features/patterns that might be visible in only one (or two) of many frames. The frame rate can be as slow as 25 frames per second and the video may contain over 7500 frames. I often start by scanning the video at high speed looking for a segment where I might find the feature, then rewind. I repeat this procedure while gradually reducing the playback speed, until I find a fairly small time window in which I can expect to find the feature (if it is present). I would then like to step forward and backward by single frames using key hit events (e.g. right arrow and left arrow keys) to find the feature of interest. I have managed to use HTML5 with JavaScript to control the forward speed; but, still do not know how to use the keyboard for single frame stepping forward and backward through a video. How can this be accomplished? Note, my web browser is Firefox 26 running on a Windows 7 platform.

Upvotes: 10

Views: 23152

Answers (2)

brianchirls
brianchirls

Reputation: 7853

You can seek to any time in the video by setting the currentTime property. Something like this:

var video = document.getElementById('video'),
    frameTime = 1 / 25; //assume 25 fps

window.addEventListener('keypress', function (evt) {
    if (video.paused) { //or you can force it to pause here
        if (evt.keyCode === 37) { //left arrow
            //one frame back
            video.currentTime = Math.max(0, video.currentTime - frameTime);
        } else if (evt.keyCode === 39) { //right arrow
            //one frame forward
            //Don't go past the end, otherwise you may get an error
            video.currentTime = Math.min(video.duration, video.currentTime + frameTime);
        }
    }        
});

Just a couple things you need to be aware of, though they shouldn't cause you too much trouble:

  1. There is no way to detect the frame rate, so you have to either hard-code it or list it in some lookup table or guess.

  2. Seeking may take a few milliseconds or more and does not happen synchronously. The browser needs some time to load the video from the network (if it's not already loaded) and to decode the frame. If you need to know when seeking is done, you can listen for the 'seeked' event.

Upvotes: 23

jacksonzumdish
jacksonzumdish

Reputation: 65

You can check to see if the video has advanced to the next frame by checking the

        targetTime += (1 / 25) // 25 fps
        video.currentTime = targetTime // set the video frame
        
        if (video.currentTime >= video.duration) { // if it's the end of the video
            alert('done!');
        }

        if (video.currentTime == targetTime) { // frame has been updated
            
        }

Upvotes: 1

Related Questions