video-sync-thing/mediaplayer.js

70 lines
1.6 KiB
JavaScript

var getVideoLength = require('video-length');
var {EventEmitter} = require("events");
class MediaPlayer extends EventEmitter {
constructor() {
super();
this.file = null;
this.mediaLength = null;
this._playment = null;
this._pausePosition = null;
}
_startPlaymentAt(position) {
if (this._playment) clearTimeout(this._playment.timeout);
this._playment = {
startedAt: Date.now(),
startPosition: position,
timeout: setTimeout(() => {
this._playment = null;
this.emit("end");
}, this.mediaLength - position)
}
}
get position() {
if (this._playment)
return this._playment.startPosition + (Date.now() - this._playment.startedAt);
else
return this._pausePosition || 0;
}
set position(position) { //seek
if (this._playment) {
this._startPlaymentAt(position);
} else {
this._pausePosition = position;
}
this.emit("pos", position);
}
get playing() {
return Boolean(this._playment);
}
async setMedia(file) {
this._pausePosition = null;
if (this._playment) clearTimeout(this._playment.timeout);
this._playment = null;
this.file = file;
this.mediaLength = (await getVideoLength(file, {bin: process.env.MEDIAINFO_BIN})) * 1000;
console.debug(this.mediaLength);
this.emit("media", file, this.mediaLength);
}
play() {
this._startPlaymentAt(this._pausePosition || 0);
this._pausePosition = null;
this.emit("play");
}
pause() {
this._pausePosition = this.position;
if (this._playment) clearTimeout(this._playment.timeout);
this._playment = null;
this.emit("pause");
}
}
module.exports = MediaPlayer;