discord.js v13使用@discordjs/voice播放音频无声音问题求助
问题排查步骤
- 缺少转码依赖
@discordjs/voice 原生仅支持 opus 编码的音频流,直接播放 mp3 格式需要额外安装转码依赖,执行以下命令安装:
- 缺少转码依赖
npm install @discordjs/opus ffmpeg-static
如果是Linux系统,也可以额外安装系统级ffmpeg:sudo apt install ffmpeg
- 音频文件路径错误
当前使用的相对路径./sound/audio.mp3是基于Node进程启动时的工作目录解析的,实际运行时很可能找不到对应文件,建议使用绝对路径定位文件,示例:
- 音频文件路径错误
// 顶部引入path、fs模块 const path = require('path'); const fs = require('fs'); // 构造音频文件绝对路径,根据你的实际文件层级调整 const audioPath = path.join(__dirname, '../../sound/audio.mp3'); // 提前判断文件是否存在 if (!fs.existsSync(audioPath)) { return message.reply('音频文件不存在'); }
- 缺少错误监听无法定位异常
原代码没有添加音频播放器的错误监听,播放失败也不会抛出可见报错,建议添加监听逻辑排查异常:
- 缺少错误监听无法定位异常
audioPlayer.on('error', error => { console.error('播放出错:', error); }); audioPlayer.on(AudioPlayerStatus.Playing, () => { console.log('正在播放音频'); }); audioPlayer.on(AudioPlayerStatus.Idle, () => { console.log('播放结束'); });
- 检查语音权限配置
确认机器人在你所在的语音频道拥有以下权限:
- 连接语音频道
- 说话
同时确认你没有在Discord客户端手动将机器人静音,也没有服务器管理员给机器人设置了服务器静音。
- 检查语音权限配置
- 补充进房参数
调用joinVoiceChannel时明确指定不自闭音、不自静音:
- 补充进房参数
const connection = joinVoiceChannel({ channelId: voiceChannel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator, selfDeaf: false, selfMute: false });
修复后完整代码示例
const path = require('path'); const fs = require('fs'); const { getVoiceConnection, joinVoiceChannel, AudioPlayerStatus, createAudioResource, createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice'); module.exports = { name: "play", category: "music", description: "plays audio", usage: "<id | mention>", run: async (client, message, args) => { const voiceChannel = message.member.voice.channel; if (!voiceChannel) return message.reply('你需要先加入语音频道'); const audioPath = path.join(__dirname, '../../sound/audio.mp3'); // 自行调整路径层级 if (!fs.existsSync(audioPath)) return message.reply('音频文件不存在'); const connection = joinVoiceChannel({ channelId: voiceChannel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator, selfDeaf: false, selfMute: false }); const audioPlayer = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause, }, }); // 事件监听 audioPlayer.on('error', error => { console.error('播放错误:', error); message.reply('播放失败:' + error.message); }); audioPlayer.on(AudioPlayerStatus.Playing, () => { console.log('音频开始播放'); }); const resource = createAudioResource(audioPath); audioPlayer.play(resource); connection.subscribe(audioPlayer); } }
内容的提问来源于stack exchange,提问作者clxne
相关产品推荐
相关产品推荐

