kannon-client/classes/Audiostream.js

84 lines
No EOL
2.6 KiB
JavaScript

const net = require('net');
const constants = require('../libs/constants');
const Message = require('./Message');
class Audiostream {
constructor(eventParser) {
this.eventParser = eventParser;
this.#handleEvents();
}
getHost() {
return this.host;
}
getPort() {
return this.port;
}
getTag() {
return this.getHost() + ':' + this.getPort();
}
#initialize(data) {
this.host = config?.server?.host || "127.0.0.1";
this.port = data.port;
this.clientId = data.clientId;
this.settings = data.settings;
this.#handleSocket(net.connect({
host: this.getHost(),
port: this.getPort()
}));
}
#handleEvents() {
this.eventParser.on('audio:initialize', (data) => {
logger.debug('handling event \'audio:initialize\'...');
this.#initialize(data);
});
this.eventParser.on(constants.AUDIO_PLAY, () => {
logger.debug('handling event \'' + constants.AUDIO_PLAY + '\'...');
global.player.play();
});
this.eventParser.on(constants.AUDIO_RESUME, () => {
logger.debug('handling event \'' + constants.AUDIO_RESUME + '\'...');
global.player.resume();
});
this.eventParser.on(constants.AUDIO_PAUSE, () => {
logger.debug('handling event \'' + constants.AUDIO_PAUSE + '\'...');
global.player.pause();
});
this.eventParser.on(constants.AUDIO_STOP, () => {
logger.debug('handling event \'' + constants.AUDIO_STOP + '\'...');
global.player.stop();
});
global.player.on(constants.STATECHANGE, (data) => {
new Message(constants.AUDIO_STATE, {
clientId: this.clientId,
state: data.state,
progress: data.progress
}).send();
});
}
#handleSocket(socket) {
socket.on('connect', async () => {
logger.debug('connected to audio server \'' + this.getTag() + '\'...');
await global.player.prepare(socket, this.settings);
new Message('audio:register', { clientId: this.clientId, port: socket.localPort }).send();
});
socket.on('error', (error) => {
logger.error('error connecting to audio server \'' + this.getTag() + '\': ' + error);
});
socket.on('close', () => {
logger.info('connection to audio server \'' + this.getTag() + '\' closed');
});
}
destroy() {
}
}
module.exports = Audiostream;