kannon-client/classes/Player.js

83 lines
No EOL
1.9 KiB
JavaScript

const EventEmitter = require('events');
const AudioBuffer = require('./AudioBuffer.js');
class Player extends EventEmitter {
constructor() {
super();
}
async prepare(stream, settings) {
logger.debug('preparing audio player...');
this.events = [];
this.settings = settings;
this.audiobuffer = new AudioBuffer(stream, this.settings);
this.audiobuffer.on(constants.THRESHOLD, () => {
this.#setState(constants.READY);
});
this.audiobuffer.on('play', () => {
this.#setState(constants.PLAYING);
});
this.audiobuffer.on('pause', () => {
this.#setState(constants.PAUSED);
});
this.audiobuffer.on('close', () => {
this.#setState(constants.STOPPED);
});
}
play() {
this.audiobuffer.play();
}
pause() {
this.audiobuffer.pause();
}
async stop() {
this.audiobuffer.stop();
}
isReady() {
return this.state === constants.READY;
}
isPlaying() {
return this.state === constants.PLAYING;
}
isPaused() {
return this.state === constants.PAUSED;
}
isFinished() {
return this.state === constants.STOPPED;
}
hasError() {
return this.state === constants.ERROR;
}
getProgress() {
return this.audiobuffer?.getProgress() || 0;
}
#setState(state, data) {
if (this.state === state) {
return;
}
this.state = state;
logger.debug('setting state of audio player to \'' + state + '\'...');
if (this.events.includes(state)) {
return;
}
logger.debug('emitting state \'' + state + '\' of audio player...');
this.emit(this.state, { data: data });
this.emit(constants.STATECHANGE, { state: this.state, progress: this.getProgress() });
this.events.push(state);
}
}
module.exports = Player;