Last active
December 22, 2015 21:57
-
-
Save positlabs/30605eccf05375da14f1 to your computer and use it in GitHub Desktop.
Respond to cuepoints during video playback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
// mapping cues to methods | |
var cuepointMethods = { | |
"1": function(){}, | |
"2.82": function(){}, | |
"3.31": function(){} | |
}; | |
// instantiate with <video>, and an array of cuepoint times => [1, 2.82, 3.31] | |
var cp = new CuePoints(document.querySelector('#video'), Object.keys(cuepointMethods)); | |
// listen for cue event | |
cp.on('cue', function(cue){ | |
// do something with the cue | |
// in this example, we map the cue to a method | |
cuepointMethods[cue](); | |
}); | |
*/ | |
window.CuePoints = function(video, cuepoints){ | |
this.video = video; | |
this.cuepoints = cuepoints; | |
video.addEventListener('play', this._onPlayVideo.bind(this)); | |
if(!video.paused) this._onPlayVideo(); | |
}; | |
// https://www.npmjs.com/package/backbone-events-standalone | |
CuePoints.prototype = BackboneEvents.mixin({}); | |
CuePoints.prototype._onPlayVideo = function(){ | |
this._prevTime = this.video.currentTime; | |
// start animationframe | |
this._onFrame(); | |
}; | |
CuePoints.prototype._onFrame = function(){ | |
// only fire cue events if video is playing. Might not be wanted in some cases... | |
if(this.video.paused) return; | |
this.cuepoints.forEach(function(cuepoint){ | |
if(cuepoint >= this._prevTime && cuepoint < this.video.currentTime){ | |
this.trigger('cue', cuepoint); | |
} | |
}.bind(this)); | |
this._prevTime = this.video.currentTime; | |
requestAnimationFrame(this._onFrame.bind(this)); | |
}; | |
CuePoints.prototype.destroy = function(){ | |
this.video.removeEventListener('play', this._onPlayVideo); | |
this.video = null; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment