function syncMedia(){};
syncMedia.prototype.syncMedia = function ( mediaMain, media ) {
var self = this;
if ( mediaMain.getAttribute( "data-syncing" ) ||
media.getAttribute( "data-syncing" ) ) {
return;
}
function sync() {
if ( !mediaMain.getAttribute( "data-syncing" ) ||
!media.getAttribute( "data-syncing" ) )
return;
if ( isNotSynced() ) {
media.currentTime = mediaMain.currentTime;
if ( !isReady( media ) || !isReady( mediaMain ) ) {
media.pause();
mediaMain.pause();
media.addEventListener( "seeked", function f() {
media.removeEventListener( "seeked", f );
self._seekedHandler = f;
wait( mediaMain, media, mediaMain.currentTime, function () {
if ( !self._notPlay && !isNotSynced() ) {
media.play();
mediaMain.play();
}
sync();
});
} );
}
return;
}
};
function isNotSynced () {
return mediaMain.currentTime - media.currentTime > 0.2 ||
mediaMain.currentTime - media.currentTime < -0.2;
}
mediaMain.setAttribute( "data-syncing", true );
media.setAttribute( "data-syncing", true );
media.addEventListener( "timeupdate", sync );
mediaMain.addEventListener( "timeupdate", sync );
//sync();
function wait( media, sMedia, time, callback ) {
var _callback = function () {
//console.log( "1", getBuffered( media, time ) );
//console.log( "2", getBuffered( sMedia, time ) );
if( isReady( media ) && isReady( sMedia )
&& getBuffered( media, time ) > 0.2
&& getBuffered( sMedia, time ) > 0.2 ) {
callback();
media.removeEventListener( "progress", _callback );
sMedia.removeEventListener( "progress", _callback);
}
};
self._progressHandler = _callback;
media.addEventListener( "progress", _callback );
sMedia.addEventListener( "progress", _callback );
_callback();
};
function isReady( media ) {
return media.readyState === media.HAVE_ENOUGH_DATA;
};
this._sync = sync;
this._notPlay = false
};
syncMedia.prototype.unSyncMedia = function ( media, sMedia ) {
sMedia.removeAttribute( "data-syncing" );
media.removeAttribute( "data-syncing" );
media.removeEventListener( "timeupdate", this._sync );
sMedia.removeEventListener( "timeupdate", this._sync );
media.removeEventListener( "progress", this._progressHandler );
sMedia.removeEventListener( "progress", this._progressHandler );
media.removeEventListener( "seeked", this._seekedHandler );
sMedia.removeEventListener( "seeked", this._seekedHandler );
};
function getBuffered ( video, currentTime ) {
var buffered = video.buffered, end;
for ( var i = 0; i < buffered.length; i++ ) {
end = buffered.end ( i );
if ( Math.floor ( buffered.start( i ) ) <= currentTime &&
end > currentTime ) {
if ( end >= video.duration ) {
return end;
}
return end - currentTime;
}
}
return 0;
}