Discord Save User Voice with VoiceReceiver
Asked Answered
A

1

6


When I'm talking on a voice channel the bot says 'I'm listening to xxx',
But when I check the /recordings folder there is a .pcm file there but its length is 0 so basically saving an empty .pcm file.

Here is the code:

const Discord = require("discord.js");

const fs = require('fs');
const client = new Discord.Client();
// const config = require('./auth.json');
// make a new stream for each time someone starts to talk
function generateOutputFile(channel, member) {
  // use IDs instead of username cause some people have stupid emojis in their name
  const fileName = `./recordings/${Date.now()}.pcm`;
  return fs.createWriteStream(fileName);
}
client.on('message', msg => {
  if (msg.content.startsWith('!join')) {
    let [command, ...channelName] = msg.content.split(" ");
    if (!msg.guild) {
      return msg.reply('no private service is available in your area at the moment. Please contact a service representative for more details.');
    }
    const voiceChannel = msg.guild.channels.find("name", channelName.join(" "));
    //console.log(voiceChannel.id);
    if (!voiceChannel || voiceChannel.type !== 'voice') {
      return msg.reply(`I couldn't find the channel ${channelName}. Can you spell?`);
    }
    voiceChannel.join()
      .then(conn => {
        msg.reply('ready!');
        // create our voice receiver
        const receiver = conn.createReceiver();
        conn.on('speaking', (user, speaking) => {
          if (speaking) {
            msg.channel.sendMessage(`I'm listening to ${user}`);
            // this creates a 16-bit signed PCM, stereo 48KHz PCM stream.
            const audioStream = receiver.createPCMStream(user);
            const outputStream = generateOutputFile(voiceChannel, user);
            audioStream.pipe(outputStream);
            outputStream.on("data", console.log);
            audioStream.on('end', () => {
              msg.channel.sendMessage(`I'm no longer listening to ${user}`);
            });
          }
        });
      })
      .catch(console.log);
  }
  if(msg.content.startsWith('!leave')) {
    let [command, ...channelName] = msg.content.split(" ");
    let voiceChannel = msg.guild.channels.find("name", channelName.join(" "));
    voiceChannel.leave();
  }
});
client.login("discord token");
client.on('ready', () => {
  console.log('ready!');
});

Is there any way to fix this problem or alternatives to save the voice of a user when speaking.

Thanks.

Adhere answered 20/2, 2019 at 12:32 Comment(1)
Did you find a way to save your voice?Microbiology
S
2

Apparently, there's a bug that if your bot doesn't play anything, it can't receive audio. Here's a fix provided in a response to the exact same problem. https://mcmap.net/q/1916268/-receive-audio-form-a-user-with-discord-bot

Straitlaced answered 11/5, 2021 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.