Search code examples
javascriptreactjsloopsoptimizationhtml5-video

What is optimal way to reverse video with html and javascript?


I'm building simple informative website for the browser. In this website I'm using video in the background the page look interesting. The problem is I wanted to video work in a certain sequence:

  • Video plays until the end
  • After video played it slows down in a half and played reverse until the 6th second of it
  • It loops between 6th second and end, and plays back and forth.

I can't find optimal way to do it.

I'm developing website on Next JS, but any abstract suggestion will work.

  1. My first solution was to create 2 different videos, one for intro and second for loop, and seamlessly change them. But I couldn't a way to make transition invisible.
  2. The second solution was to manipulate video with animation library GSAP, but video lagged a lot.
  3. And third and currently the best attempt is to just change currentTime property in the video object itself inside of setInterval funciton
const playForward = () => {
    const video = videoRef.current!;
    if (loopIntervalRef.current) {
      clearInterval(loopIntervalRef.current);
    }

    //@ts-ignore
    loopIntervalRef.current = setInterval(() => {
      if (video.currentTime >= video.duration) {
        playBack();
      } else {
        video.currentTime += 0.04;
      }
    }, 120);
  };
 const playBack = () => {
    const video = videoRef.current!;
    if (loopIntervalRef.current) {
      clearInterval(loopIntervalRef.current);
    }

    //@ts-ignore
    loopIntervalRef.current = setInterval(() => {
      if (video.currentTime <= reversePoint) {
        playForward();
      } else {
        video.currentTime -= 0.04;
      }
    }, 120);
  };

It works almost perfectly, but video lagging sometimes while playing reverse.


Solution

  • I think you should have two copies of the video, one normal and one reversed and to toggle between the two when they reach the end.

    Luckily, the well known ffmpeg utility can create a copy in reverse using the following syntax...

    ffmpeg -i /storage/emulated/0/ffvid/frameCount.mp4 -vf reverse -af areverse reversed.mp4
    

    As informed on this page.