You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js机器人加入语音频道后无法播放声音问题求助

解决Discord机器人无法播放音频的问题

1. 补充缺失的语音相关意图

客户端缺少GatewayIntentBits.GuildVoiceStates意图,这是处理语音频道状态逻辑的必要项,缺失可能导致音频连接底层异常。

修改客户端初始化代码:

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildVoiceStates // 新增该意图
  ],
});

2. 添加错误监听排查问题

代码未监听音频播放器和资源的错误事件,导致无法捕获潜在异常。在messageCreate事件中添加错误监听:

client.on('messageCreate', (message) => {
  if (message.content === 'hello') {
    const connection = joinVoiceChannel({
      channelId: message.member.voice.channel.id,
      guildId: message.member.voice.guild.id,
      adapterCreator: message.member.voice.guild.voiceAdapterCreator,
      selfDeaf: false,
    });
    const player = createAudioPlayer();
    // 监听播放器错误
    player.on('error', error => {
      console.error(`播放器错误: ${error.message}`, error);
    });
    connection.subscribe(player);
    // 声明resource变量并监听音频流错误
    const resource = createAudioResource(path.join(__dirname, 'sounds', 'alert.mp3'));
    resource.playStream.on('error', error => {
      console.error(`音频流错误: ${error.message}`, error);
    });
    player.play(resource);
  }
});

3. 检查并安装完整依赖

@discordjs/voice依赖@discordjs/opus和ffmpeg-static(或系统已安装ffmpeg),缺失会导致音频无法解码播放。执行以下命令安装依赖:

npm install @discordjs/opus ffmpeg-static

4. 验证音频文件格式

确保alert.mp3为标准MP3格式(推荐采样率48kHz),非标准编码的音频文件可能无法被正常解码。可替换为已知可用的MP3文件测试。

5. 优化播放器复用(可选)

全局已创建player变量,无需在messageCreate事件中重复创建,可复用全局播放器并清理之前的播放任务:

client.on('messageCreate', (message) => {
  if (message.content === 'hello') {
    const connection = joinVoiceChannel({
      channelId: message.member.voice.channel.id,
      guildId: message.member.voice.guild.id,
      adapterCreator: message.member.voice.guild.voiceAdapterCreator,
      selfDeaf: false,
    });
    connection.subscribe(player);
    // 停止之前的播放任务
    player.stop();
    const resource = createAudioResource(path.join(__dirname, 'sounds', 'alert.mp3'));
    player.play(resource);
  }
});

内容的提问来源于stack exchange,提问作者Unskilled

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:16:30