kannon-client/classes/Audiostream.js

78 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-04-14 14:25:48 +02:00
const net = require('net');
2022-04-20 16:15:51 +02:00
const { sleep } = require('../libs/util');
2022-04-14 14:25:48 +02:00
const Message = require('./Message');
class Audiostream {
2022-04-20 16:15:51 +02:00
constructor(eventParser) {
this.eventParser = eventParser;
this.#handleEvents();
2022-04-14 14:25:48 +02:00
}
getHost() {
return this.host;
}
getPort() {
return this.port;
}
getTag() {
return this.getHost() + ':' + this.getPort();
}
2022-04-20 16:15:51 +02:00
#initialize(data) {
this.host = config?.server?.host || "127.0.0.1";
this.port = data.port;
this.clientId = data.clientId;
this.threshold = data.threshold;
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('audio:play', (data) => {
logger.debug('handling event \'audio:play\'...');
// global.player.play(data?.position);
global.player.play();
2022-04-20 16:15:51 +02:00
});
this.eventParser.on('audio:pause', (data) => {
logger.debug('handling event \'audio:pause\'...');
global.player.pause();
});
this.eventParser.on('audio:stop', () => {
logger.debug('handling event \'audio:stop\'...');
global.player.stop();
});
global.player.on('statechange', (data) => {
new Message('audio:state', {
clientId: this.clientId,
state: data.state,
position: global.player.getPosition()
}).send();
});
}
2022-04-14 14:25:48 +02:00
#handleSocket(socket) {
2022-04-21 13:40:00 +02:00
socket.on('connect', async () => {
2022-04-14 14:25:48 +02:00
logger.debug('connected to audio server \'' + this.getTag() + '\'...');
await global.player.prepare(this.threshold, socket);
2022-04-21 13:40:00 +02:00
new Message('audio:register', { clientId: this.clientId, port: socket.localPort }).send();
2022-04-14 14:25:48 +02:00
});
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');
// global.player.stopFeed();
2022-04-14 14:25:48 +02:00
});
}
}
module.exports = Audiostream;