如何使用整数暂停基于video.currentTime的视频?

时间:2016-03-14 17:23:47

标签: javascript jquery video html5-video

<video id="js-video" autoplay>
   <source src="./vid.mp4" type="video/mp4">
</video> 
<button id="js-button">
</button>

var video = document.getElementById('js-video');
var button = document.getElementById('js-button');
var data = [
     { pauseTime: 2,
       image: "./foo_1.png"
     },{
      pauseTime: 6,
      image: "./foo_2.png"
     }
    ];

    function showOverlay() {
     video.addEventListener('timeupdate', function() {
      var full = parseInt(video.currentTime);

        console.log(video.currentTime);

      for (var i=0; i < data.length; i++) {
        if (full === data[i].pauseTime) {
          video.pause();
          moveToNextScene();
        } else {
          console.log("else");
        }
      }
     });
    }

   function moveToNextScene() {
      button.addEventListener('click', function() {
        video.play();
      });
    }

    showOverlay();

我有一个视频并使用数据阵列,我想暂停数据阵列内对象中pauseTime的视频,并在其上面放置一个叠加图像。

我遇到的问题是timeUpdate事件会返回一个十进制数字,因此我必须在其上调用parseInt,但在这种情况下,视频会在2之间的所有间隔保持暂停状态整数,例如:如果我想在2秒暂停,它会在2.000001之间暂停几次,一直到2.999999,但我只想让它在2.000001左右暂停一次(不一定要精确)并且没有更多,直到下一个pauseTime,在这种情况下6。 我在video[0].currentTime += 1;语句中写了if,它修复了这个问题,但是它跳了一秒钟,我不想要那个。

你可以在这里看到我的意思:https://jsfiddle.net/njbn0ddn/1/

1 个答案:

答案 0 :(得分:1)

我认为你需要一种更正式的方式来注意事件的完成。在这里我们注意到我们已经达到了停止点,如果有,我们继续前进而不再检查时间。这是更新的小提琴:https://jsfiddle.net/meqnz2vj/

var video = document.getElementById('js-video');
    var button = document.getElementById('js-button');
    var data = [
         { pauseTime: 2,
           image: "./foo_1.png",
           got_here:false
         },{
          pauseTime: 6,
          image: "./foo_2.png",
          got_here:false
         }
        ];

        function showOverlay() {
         video.addEventListener('timeupdate', function() {
          var full = parseInt(video.currentTime);

            console.log(video.currentTime);

          for (var i=0; i < data.length; i++) {
            if (full === data[i].pauseTime && data[i].got_here == false) {
              data[i].got_here = true;
              video.pause();
              moveToNextScene();
            } else {
              console.log("else");
            }
          }
         });
        }

       //when paused, a button will appear, on closing it, the vide resumes
       function moveToNextScene() {
          button.addEventListener('click', function() {
            video.play();
          });
        }

        showOverlay();