如何用js向后播放视频?

how to play a video backwards with js?

<video id="vid" controls>
   <source src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/twitter_cat.mp4"  type="video/mp4">
</video>
<script>
    window.onload=()=>{
        const vid= document.getElementById("vid");
        vid.currentTime=4;
        vid.playbackRate=-0.5;
        vid.play();
    }
    
</script>

我试过了,但是没有用,有没有办法倒放视频?

这很复杂,但是大多数视频格式和压缩类型都是为了向前播放,像这样:

  1. 原始素材已上传
  2. 选择了几个关键帧,大部分视频都基于这些关键帧。
  3. 压缩软件会跟踪上一帧和当前帧之间的变化。它可能类似于“这个区域从黑色变为灰色”或“这个蓝色像素点向上移动”
  4. 丢弃非关键帧,仅保留更改

如您所见,这会在尝试向后播放时造成很大的问题,因为构成帧的变化是基于帧的变化,而帧的变化是基于变化的帧.. ..关键帧。向前播放不是问题,因为您不必返回到最后一个 关键帧 并跟踪更改,最后一帧就在您面前.尽管有蛮力的方法可以逆向进行 (see here),但这些方法通常很慢并且占用大量内存。不幸的是,你的问题的最佳答案是你不能。

许多视频格式都是 Streaming Media 设计用于向前播放的格式。

向后播放需要解码整个流,将每个原始帧存储在磁盘上以避免破坏内存,然后向后渲染帧。

TMLVideoElement.prototype.playBackwards = function() {
this.pause();

    var video = this;

    var fps = 25;
    var intervalRewind = setInterval(function() {
        if(video.currentTime == 0){
            clearInterval(intervalRewind);
            video.pause();
        } else {
            video.currentTime += -(1/fps);
        }
    }, 1000 / fps);
};

我的丑陋行为,只需在初始 canplay 事件触发后寻找 seeked 事件,从该点向后搜索几帧。

(function() {
  var playbackSpeed = .05
  var video = document.getElementById('vid')

  video.addEventListener('canplay', function() {
    if (!this.started) {
      this.started = true
      this.play()
      this.currentTime = this.duration - .01
    }
  })

  video.addEventListener('seeked', function() {
    this.currentTime = this.currentTime <= 0.01 ? 
      this.duration - .01 : this.currentTime - playbackSpeed
  })
}())
<video id="vid" controls>
  <source
    src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/twitter_cat.mp4"
    type="video/mp4"
  />
</video>