如何为HTML5视频播放器创建偏移插件

时间:2015-09-24 09:36:55

标签: javascript jquery html5 video

我试图创建一个偏移插件来播放HTML5视频播放器中完整视频的部分视频,但 video.js 可以使用该插件 videojs-offset plugin,现在我正在尝试将此插件转换为仅与HTML5播放器配合使用

videojs偏移插件的来源

(function() {
    "use strict";
    var a = function(a) {
        var b;
        return this._offsetStart = a.start || 0, this._offsetEnd = a.end || 0, b = this.constructor, b.__super__ && b.__super__.__offsetInit || (b.__super__ = {
            __offsetInit: !0,
            duration: b.prototype.duration,
            currentTime: b.prototype.currentTime,
            bufferedPercent: b.prototype.bufferedPercent,
            remainingTime: b.prototype.remainingTime
        }, b.prototype.duration = function() {
            return this._offsetEnd > 0 ? this._offsetEnd - this._offsetStart : b.__super__.duration.apply(this, arguments) - this._offsetStart
        }, b.prototype.currentTime = function(a) {
            return void 0 !== a ? b.__super__.currentTime.call(this, a + this._offsetStart) - this._offsetStart : b.__super__.currentTime.apply(this, arguments) - this._offsetStart
        }, b.prototype.remainingTime = function() {
            var a = this.currentTime();
            return a < this._offsetStart && (a = 0), this.duration() - a
        }, b.prototype.startOffset = function() {
            return this._offsetStart
        }, b.prototype.endOffset = function() {
            return this._offsetEnd > 0 ? this._offsetEnd : this.duration()
        }), this.on("timeupdate", function() {
            var a = this.currentTime();
            0 > a && (this.currentTime(0), this.play()), this._offsetEnd > 0 && a > this._offsetEnd - this._offsetStart && (this.currentTime(this._offsetEnd - this._offsetStart), this.pause())
        }), this
    };
    a.VERSION = "0.0.0", window.vjsoffset = a, window.videojs.plugin("offset", a)
}).call(this);

我需要尝试的方法是单独使用HTML5视频播放器吗?

1 个答案:

答案 0 :(得分:1)

这似乎是您可以使用最少量的代码轻松完成的事情。我建议写这样的东西:

function videoSegment(elementOrQuery, start, stop){
  
  var element = typeof elementOrQuery === 'string'
    ? document.querySelector(elementOrQuery) : elementOrQuery;
  
  element.currentTime = start;
  
  // While playing, check if time is within bounds
  element.addEventListener('timeupdate', function(){
    if(element.currentTime < start) element.currentTime = start;
    if(element.currentTime > stop) element.pause();
  });
  // When starting to play make sure its within bounds
  element.addEventListener('play', function(){
    if(element.duration > stop || element.duration < start) element.currentTime = start;
  });
  // When pausing, check if theres a loop and repeat or reset to beginning
  element.addEventListener('pause', function(){
    if(element.currentTime > stop) element.currentTime = start;
    if(element.loop) element.play();
  });
  
}

videoSegment('video', 2, 4);
<video controls autoplay loop>
  <source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>