kannon-client/classes/Speaker.js

82 lines
2.6 KiB
JavaScript
Raw Normal View History

const NodeSpeaker = require('speaker');
const createReadStream = require('fs').createReadStream;
class Speaker {
constructor(channels, bitDepth, sampleRate) {
this.#handlePlayer(channels, bitDepth, sampleRate);
this.playback = {
played: 0,
tmp: 0
};
}
pipe(data) {
return this.speaker.write(data);
}
// pipe(buffer, position) {
// if (buffer === undefined) {
// return;
// }
// this.playback.stream = createReadStream(file);
// if (isNaN(position) || position < 0) {
// position = 0;
// }
// position = 65537* 100;
// this.playback.stream.on('data', (data) => {
// if (position > 0 && this.playback.played <= position) {
// const offset = position - (this.playback.played + data.length);
// if (offset >= 0) {
// this.playback.played += data.length;
// return;
// }
// data = data.subarray(data.length + offset);
// }
// if (this.speaker.write(data) === true) {
// this.playback.played += data.length;
// } else {
// this.playback.tmp = data.length;
// this.playback.stream.pause();
// }
// });
// this.playback.stream.on('end', () => {
// logger.debug('read stream ended');
// });
// this.playback.stream.on('close', () => {
// logger.debug('read stream closed');
// });
// this.playback.stream.on('drain', () => {
// logger.debug('read stream drained');
// });
// this.playback.stream.on('error', (error) => {
// logger.debug('read stream encountered an error: ' + error);
// });
// }
#handlePlayer(channels, bitDepth, sampleRate) {
this.speaker = new NodeSpeaker({
channels: channels,
bitDepth: bitDepth,
sampleRate: sampleRate
});
this.speaker.on('open', () => {
logger.debug('speaker opened...');
});
this.speaker.on('flush', () => {
logger.debug('speaker flushed...');
});
this.speaker.on('close', () => {
logger.debug('speaker closed...');
});
this.speaker.on('drain', () => {
// handle backpressure
// this.playback.played += this.tmp;
// this.playback.tmp = 0;
// this.playback.stream.resume();
});
}
}
module.exports = Speaker;