Create basic voice receiving

This commit is contained in:
Amish Shah
2016-08-25 22:40:16 +01:00
parent 8038903c3e
commit 2d6068010b
4 changed files with 57 additions and 1 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,6 @@
const VoiceConnectionWebSocket = require('./VoiceConnectionWebSocket');
const VoiceConnectionUDPClient = require('./VoiceConnectionUDPClient');
const VoiceReceiver = require('./receiver/VoiceReceiver');
const Constants = require('../../util/Constants');
const EventEmitter = require('events').EventEmitter;
const DefaultPlayer = require('./player/DefaultPlayer');
@@ -179,6 +180,14 @@ class VoiceConnection extends EventEmitter {
playStream(stream) {
return this.player.playStream(stream);
}
/**
* Creates a VoiceReceiver so you can start listening to voice data. It's recommended to only create one of these.
* @returns {VoiceReceiver}
*/
createReceiver() {
return new VoiceReceiver(this);
}
}
module.exports = VoiceConnection;

View File

@@ -0,0 +1,45 @@
const EventEmitter = require('events').EventEmitter;
const NaCl = require('tweetnacl');
const nonce = new Buffer(24);
nonce.fill(0);
/**
* Receives voice data from a voice connection.
* @extends {EventEmitter}
*/
class VoiceReceiver extends EventEmitter {
constructor(connection) {
super();
/**
* The VoiceConnection that instantiated this
* @type {VoiceConnection}
*/
this.connection = connection;
this.connection.udp.udpSocket.on('message', msg => {
msg.copy(nonce, 0, 0, 12);
let data = NaCl.secretbox.open(msg.slice(12), nonce, this.connection.data.secret);
if (!data) {
return this.emit('warn', 'failed to decrypt voice packet');
}
data = new Buffer(data);
/**
* Emitted whenever voice data is received from the voice connection. This is _always_ emitted (unlike PCM).
* @event VoiceReceiver#opus
* @param {Buffer} buffer the opus buffer
*/
this.emit('opus', data);
if (this.listenerCount('pcm') > 0) {
/**
* Emits decoded voice data when it's received. For performance reasons, the decoding will only
* happen if there is at least one `pcm` listener on this receiver.
* @event VoiceReceiver#pcm
* @param {Buffer} buffer the decoded buffer
*/
this.emit('pcm', this.connection.player.opusEncoder.decode(data));
}
});
}
}
module.exports = VoiceReceiver;

View File

@@ -144,6 +144,8 @@ client.on('message', msg => {
const disp = conn.player.playStream(ytdl('https://www.youtube.com/watch?v=nbXgHAzUWB0', {filter : 'audioonly'}));
conn.player.on('debug', console.log);
conn.player.on('error', err => console.log(123, err));
const receiver = conn.createReceiver();
receiver.on('pcm', console.log);
disp.on('error', err => console.log(123, err));
})
.catch(console.log);