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

Discord机器人连接语音频道后无音频输出问题求助

问题诊断与修复方案

核心问题:播放器未与语音连接绑定

你的代码创建了语音连接和音频播放器,但没有将播放器订阅到连接上,这是导致无声音的关键原因。除此之外还有几处代码错误需要修正:


具体修复点

  1. 绑定播放器与语音连接
    创建播放器后必须调用 connection.subscribe(player),否则连接无法传递音频流。

  2. 修复wait函数未定义问题
    代码里的await wait(5000)会报错,替换为原生的Promise延迟写法。

  3. 避免使用全局arguments变量
    自定义变量名,并用正确的数组方法处理参数(shift(2)是错误用法,shift()只接受0个参数,要截取参数用slice)。

  4. 设置播放器的无订阅行为
    创建播放器时指定NoSubscriberBehavior.Play,确保无人订阅时也能继续播放。

  5. 移除无效依赖包
    package.json里的"node.js": "^0.0.1-security"是无效包,直接删除——node.js是运行环境而非npm依赖。

  6. 检查音频文件路径
    确保../music/123.mp3路径正确,可改用绝对路径排查,比如path.resolve(__dirname, '../music/123.mp3')(需引入path模块)。


修复后的完整代码

const { createAudioResource, createAudioPlayer, joinVoiceChannel, NoSubscriberBehavior } = require('@discordjs/voice');
const path = require('path'); // 引入path模块处理路径

module.exports = {
  name: "play",
  async execute(message, args, client ) {
    // 替换错误的arguments处理,用自定义变量截取参数
    const trackArgs = args.slice(2);
   
    const connection = joinVoiceChannel({
      channelId: message.member.voice.channelId,
      guildId: message.guildId,
      adapterCreator: message.guild.voiceAdapterCreator
    });

    // 创建播放器时设置无订阅行为
    const player = createAudioPlayer({
      behaviors: {
        noSubscriber: NoSubscriberBehavior.Play
      }
    });
    // 使用绝对路径确保文件能被找到
    const resource = createAudioResource(path.resolve(__dirname, '../music/123.mp3'));

    player.play(resource, {seek: 0, volume: 1.0});
    // 绑定播放器到连接
    connection.subscribe(player);
  
    // 替换未定义的wait函数
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log("time");
    connection.destroy();
  }
};

修复后的依赖包配置

"dependencies": {
    "@discordjs/builders": "^1.2.0",
    "@discordjs/opus": "^0.8.0",
    "@discordjs/rest": "^1.1.0",
    "@discordjs/voice": "^0.11.0",
    "discord-api-types": "^0.37.8",
    "discord.js": "^14.3.0",
    "ffmpeg-static": "^5.1.0",
    "libsodium-wrappers": "^0.7.10",
    "ms": "^2.1.3",
    "redis": "^4.3.1"
  }

额外检查项

  • 确保机器人在语音频道里有发言权限和连接权限
  • 运行npx @discordjs/voice generate-dependency-report检查音频依赖是否正常加载
  • 测试音频文件本身是否可正常播放,排除文件损坏问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:35:18