discord.js v14中语音频道音频录制:如何将AudioReceiveStream写入MP3文件
discord.js v14中语音频道音频录制:如何将AudioReceiveStream写入MP3文件
嘿,我来帮你解决这个问题!你现在遇到的核心问题是:AudioReceiveStream输出的是原始PCM音频数据,这种格式没法直接存成MP3文件,必须先经过转码处理。下面是具体的实现步骤,我会一步步给你讲清楚:
第一步:准备必要的工具与依赖
首先得搞定转码需要的工具和库:
- 你的系统需要安装FFmpeg(用来把PCM转成MP3):
- Windows:去FFmpeg官网下载二进制包,解压后把
bin目录添加到系统环境变量里 - Linux:用包管理器安装,比如
sudo apt install ffmpeg - macOS:用Homebrew安装,
brew install ffmpeg
- Windows:去FFmpeg官网下载二进制包,解压后把
- 安装Node.js的FFmpeg封装库
fluent-ffmpeg:npm install fluent-ffmpeg
第二步:修正代码实现录制与转码
你之前的代码里直接new AudioReceiveStream()是不对的,得从语音连接的receiver对象订阅特定用户的音频流。下面是完整的修改后的代码:
const voiceModule = require('@discordjs/voice'); const ffmpeg = require('fluent-ffmpeg'); const fs = require('fs'); async function voiceListener(interaction) { // 获取语音连接 const connection = voiceModule.getVoiceConnection(interaction.guildId); if (!connection) { await interaction.reply('当前没有活跃的语音连接哦!'); return; } // 订阅发起命令用户的音频流(可以替换成其他用户ID) const userId = interaction.member.id; const audioStream = connection.receiver.subscribe(userId, { end: { behavior: voiceModule.EndBehaviorType.Manual, // 手动控制流结束 }, }); // 设置FFmpeg转码参数:匹配Discord的PCM格式,输出为MP3 const outputPath = './recorded_audio.mp3'; ffmpeg(audioStream) .inputFormat('s16le') // Discord的PCM是16位小端格式 .audioFrequency(48000) // Discord语音采样率固定48kHz .audioChannels(1) // 单声道 .audioCodec('libmp3lame') // 使用MP3编码器 .save(outputPath) .on('start', () => { console.log(`开始录制用户 ${userId} 的音频,将保存到 ${outputPath}`); interaction.reply(`开始录制你的音频啦!输入!stop可以结束录制~`); }) .on('end', () => { console.log(`录制完成,文件已保存到 ${outputPath}`); interaction.followUp(`录制结束啦!音频文件已保存好~`); }) .on('error', (err) => { console.error('转码出错了:', err); interaction.followUp(`录制出错了:${err.message}`); connection.receiver.unsubscribe(userId); // 出错后取消订阅 }); // 监听用户的结束命令 const collector = interaction.channel.createMessageCollector({ filter: msg => msg.author.id === userId && msg.content === '!stop', max: 1, }); collector.on('collect', () => { audioStream.destroy(); // 销毁音频流 connection.receiver.unsubscribe(userId); // 取消订阅 collector.stop(); }); }
关键细节说明
- Discord的语音流参数是固定的:48kHz采样率、16位小端、单声道,FFmpeg的输入参数必须完全对应,不然转出来的MP3会有杂音或者播放异常。
- 你可以根据需求修改输出路径、文件名,甚至扩展逻辑同时录制多个用户的音频(每个用户对应一个独立的流)。
- 记得处理错误和流的结束逻辑,避免内存泄漏哦!
备注:内容来源于stack exchange,提问作者Lệ Kiệt
相关产品推荐
相关产品推荐

