kannon-client/classes/Player.js

80 lines
1.9 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.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();
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();
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() || 0;
2022-04-14 14:25:48 +02:00
}
#setState(state, data) {
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);
}
}
module.exports = Player;