Discord使用VoiceReceiver保存用户语音

时间:2019-02-20 12:32:09

标签: node.js discord discord.js pcm


当我在语音通道上聊天时,机器人会说“我在听xxx”,
但是当我检查/ recordings文件夹时,那里有一个.pcm文件,但是它的长度为0,因此基本上保存了一个空的.pcm文件。

代码如下:

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!');
});

有什么方法可以解决此问题,也可以采取其他方法来节省用户讲话时的声音。

谢谢。

1 个答案:

答案 0 :(得分:1)

显然,如果您的机器人不播放任何内容,它就无法接收音频。这是针对完全相同的问题提供的修复程序。 https://stackoverflow.com/a/65032328/11586320