0

I have a standard HTML5 video element. I would like to pause the video at specific frames (not minutes) via pure JavaScript.

<video id="media-video" controls>
    <source id="media-source" src="media/video.mp4" type="video/mp4">
</video>

Also given is a JavaScript array, which defines frames, where the video should stop.

var stopframes = [300, 600, 900];

Unfortunately, I have only a solution for stopping the video at a specific time by seconds:

video.addEventListener('timeupdate', function () {
    if (mediaPlayer.currentTime > stopframes[0]) {
        ...
    }
});

How can I stop the video at one specific frame with pure JavaScript?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
carapaece
  • 331
  • 4
  • 15

1 Answers1

2

You can use VideoFrame.js for this.

stopVideoFor takes some amount of milliseconds that I use to stop the video whenever the current frame is in stopframes (if (stopframes.includes(frame)) {):

var stopframes = [30, 60, 90, 132];

var currentFrame = $('#currentFrame');
var video = VideoFrame({
  id: 'video',
  frameRate: 29.97,
  callback: function(frame) {
    if (stopframes.includes(frame)) {
      stopVideoFor(1000);
    }
  }
});

function stopVideoFor(ms) {
  video.video.pause();
  video.stopListen();

  setTimeout(() => {
    video.video.play();
    video.listen('frame');
  }, ms);
}

$('#play-pause').click(function() {
  if (video.video.paused) {
    video.video.play();
    video.listen('frame');
    $("#play-pause").html('Pause');
  } else {
    video.video.pause();
    video.stopListen();
    $("#play-pause").html('Play');
  }
});
<script src="https://rawgit.com/allensarkisyan/VideoFrame/master/VideoFrame.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<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>
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • Thanks for pointing us to this. Unfortunately, it is not always frame-precise as I reported here: https://stackoverflow.com/questions/70613008/javascript-frame-precise-video-stop. In case you have some ideas, I'm happy to hear them – tobiasBora Jan 06 '22 at 20:33