kannon-client/classes/Player.js

89 lines
2 KiB
JavaScript
Raw Normal View History

2022-04-14 14:25:48 +02:00
const EventEmitter = require('events');
const AudioBuffer = require('./AudioBuffer.js');
2022-04-14 14:25:48 +02:00
class Player extends EventEmitter {
constructor() {
super();
this.events = [];
}
async prepare(stream, settings) {
2022-04-14 14:25:48 +02:00
logger.debug('preparing audio player...');
this.#reset();
this.audiobuffer = new AudioBuffer(stream, settings);
this.audiobuffer.on(constants.THRESHOLD, () => {
this.#setState(constants.READY);
});
this.audiobuffer.on('close', () => {
this.#setState(constants.STOPPED);
});
this.audiobuffer.on('play', () => {
this.#setState(constants.PLAYING);
});
this.audiobuffer.on('pause', () => {
this.#setState(constants.PAUSED);
})
}
play() {
this.audiobuffer.resume();
2022-04-14 14:25:48 +02:00
}
pause() {
this.audiobuffer.pause();
2022-04-14 14:25:48 +02:00
}
async stop() {
this.audiobuffer.stop();
this.#reset();
this.#setState(constants.STOPPED);
2022-04-14 14:25:48 +02:00
}
isReady() {
return this.state === constants.READY;
2022-04-14 14:25:48 +02:00
}
isPlaying() {
return this.state === constants.PLAYING;
2022-04-14 14:25:48 +02:00
}
isPaused() {
return this.state === constants.PAUSED;
2022-04-14 14:25:48 +02:00
}
isFinished() {
return this.state === constants.STOPPED;
2022-04-14 14:25:48 +02:00
}
hasError() {
return this.state === constants.ERROR;
2022-04-20 16:15:51 +02:00
}
getProgress() {
return this.audiobuffer?.getProgress();
2022-04-14 14:25:48 +02:00
}
#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;
}
2022-04-14 15:26:46 +02:00
logger.debug('emitting state \'' + state + '\' of audio player...');
2022-04-20 16:15:51 +02:00
this.emit(this.state, { data: data });
this.emit(constants.STATECHANGE, { state: this.state, progress: this.getProgress() });
2022-04-14 14:25:48 +02:00
this.events.push(state);
}
#reset() {
2022-04-14 14:25:48 +02:00
this.events = [];
}
}
module.exports = Player;