从选定的时长循环播放视频

时间:2019-05-16 09:45:33

标签: javascript jquery html5 video

2秒后我无法播放视频。视频暂停后应循环播放。我不确定要实现它。该功能可以正常运行,但不会循环。

function playVideo() {
  var starttime = 0; // start at 0 seconds
  var endtime = 2; // stop at 2 seconds
  var video = document.getElementById('videoElm');

  video.addEventListener("timeupdate", function() {
    if (this.currentTime >= endtime) {
      this.pause();
      //  SHOULD LOOP HERE? 
    }
  }, false);

  //suppose that video src has been already set properly
  video.load();
  video.play();
  try {
    video.currentTime = starttime;
  } catch (ex) {
    //handle exceptions here
  }
}

playVideo();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <video id="videoElm" autoplay muted controls loop>
    <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
  </video>
</div>

2 个答案:

答案 0 :(得分:3)

如果您希望视频在2秒后立即返回到开始并继续播放,只需将currentTime内的0设置回timeupdate。您当前的逻辑设置currentTime放置在错误的位置,周围的try/catch是不必要的。试试这个:

var starttime = 0; // start at 0 seconds
var endtime = 2; // stop at 2 seconds
var video = document.getElementById('videoElm');

function playVideo() {
  video.addEventListener("timeupdate", function() {
    if (this.currentTime >= endtime) {
      this.currentTime = 0; // change time index here
    }
  }, false);

  video.load();
  video.play();
}

playVideo();
<div>
  <video id="videoElm" autoplay muted controls loop>
    <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
  </video>
</div>

答案 1 :(得分:0)

您可以将其放在您的代码中

function playVideo() {
  var starttime = 0; // start at 0 seconds
  var endtime = 2; // stop at 2 seconds
  var video = document.getElementById('videoElm');

  video.addEventListener("timeupdate", function() {
    if (this.currentTime >= endtime) {
      this.pause();
      starttime = 0;
      playVideo();
    }
  }, false);

  //suppose that video src has been already set properly
  video.load();
  video.play();
  try {
    video.currentTime = starttime;
  } catch (ex) {
    //handle exceptions here
  }
}

playVideo();