buddy

node MVC discord bot
Log | Files | Refs | README

Receiver.js (2187B)


      1 'use strict';
      2 
      3 const EventEmitter = require('events');
      4 const prism = require('prism-media');
      5 const PacketHandler = require('./PacketHandler');
      6 const { Error } = require('../../../errors');
      7 
      8 /**
      9  * Receives audio packets from a voice connection.
     10  * @example
     11  * const receiver = connection.createReceiver();
     12  * // opusStream is a ReadableStream - that means you could play it back to a voice channel if you wanted to!
     13  * const opusStream = receiver.createStream(user);
     14  */
     15 class VoiceReceiver extends EventEmitter {
     16   constructor(connection) {
     17     super();
     18     this.connection = connection;
     19     this.packets = new PacketHandler(this);
     20     /**
     21      * Emitted whenever there is a warning
     22      * @event VoiceReceiver#debug
     23      * @param {Error|string} error The error or message to debug
     24      */
     25     this.packets.on('error', err => this.emit('debug', err));
     26   }
     27 
     28   /**
     29    * Options passed to `VoiceReceiver#createStream`.
     30    * @typedef {Object} ReceiveStreamOptions
     31    * @property {string} [mode='opus'] The mode for audio output. This defaults to opus, meaning discord.js won't decode
     32    * the packets for you. You can set this to 'pcm' so that the stream's output will be 16-bit little-endian stereo
     33    * audio
     34    * @property {string} [end='silence'] When the stream should be destroyed. If `silence`, this will be when the user
     35    * stops talking. Otherwise, if `manual`, this should be handled by you.
     36    */
     37 
     38   /**
     39    * Creates a new audio receiving stream. If a stream already exists for a user, then that stream will be returned
     40    * rather than generating a new one.
     41    * @param {UserResolvable} user The user to start listening to.
     42    * @param {ReceiveStreamOptions} options Options.
     43    * @returns {ReadableStream}
     44    */
     45   createStream(user, { mode = 'opus', end = 'silence' } = {}) {
     46     user = this.connection.client.users.resolve(user);
     47     if (!user) throw new Error('VOICE_USER_MISSING');
     48     const stream = this.packets.makeStream(user.id, end);
     49     if (mode === 'pcm') {
     50       const decoder = new prism.opus.Decoder({ channels: 2, rate: 48000, frameSize: 960 });
     51       stream.pipe(decoder);
     52       return decoder;
     53     }
     54     return stream;
     55   }
     56 }
     57 
     58 module.exports = VoiceReceiver;