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

Discord.js机器人无法播放指定本地音频资源求助

Discord.js机器人无法播放本地音频问题

我正在通过Discord.js官方文档从零开发Discord机器人,预期功能是加入语音频道并播放本地音频,但目前机器人仅能加入频道却无法播放音频。

已尝试的解决措施:

  • 添加GuildVoiceStates意图
  • 加入Reddit帖子中提到的entersState方法(不清楚其作用)

问题仍未解决,以下是相关信息:

Resource对象输出

######### RESOURCE OBJECT ##############
resource:  AudioResource {
  playStream: OggDemuxer {
    _events: {
      close: [Array],
      error: [Array],
      prefinish: [Function: prefinish],
      finish: [Array],
      drain: undefined,
      data: undefined,
      end: [Array],
      readable: [Function],
      unpipe: [Function: onunpipe]
    },
    _readableState: ReadableState {
      highWaterMark: 16,
      buffer: [],
      bufferIndex: 0,
      length: 0,
      pipes: [],
      awaitDrainWriters: null,
      Symbol(kState): 9478413
    },
    _writableState: WritableState {
      highWaterMark: 16384,
      length: 0,
      corked: 0,
      onwrite: [Function: bound onwrite],
      writelen: 0,
      bufferedIndex: 0,
      pendingcb: 0,
      Symbol(kState): 17580812,
      Symbol(kBufferedValue): null
    },
    allowHalfOpen: true,
    _maxListeners: undefined,
    _eventsCount: 7,
    _remainder: null,
    _head: null,
    _bitstream: null,
    Symbol(shapeMode): true,
    Symbol(kCapture): false,
    Symbol(kCallback): null
  },
  edges: [
    {
      type: 'ffmpeg ogg',
      to: [Node],
      cost: 2,
      transformer: [Function: transformer],
      from: [Node]
    },
    {
      type: 'ogg/opus demuxer',
      to: [Node],
      cost: 1,
      transformer: [Function: transformer],
      from: [Node]
    }
  ],
  metadata: null,
  volume: undefined,
  encoder: undefined,
  audioPlayer: undefined,
  playbackDuration: 0,
  started: false,
  silencePaddingFrames: 5,
  silenceRemaining: -1
}

代码片段

async execute(interaction) {
    const member = interaction.member;

    const channel = member.guild.channels.cache.get(interaction.channelId);

    if (channel.type !== ChannelType.GuildVoice) {
        return interaction.reply("You can call /join only within a voice channel.");
    }

    const voiceConnection = joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        adapterCreator: channel.guild.voiceAdapterCreator,
        selfDeaf: false,
    });

    const player = createAudioPlayer();
    const resource = createAudioResource(__path);

    voiceConnection.subscribe(player);

    try {
        await entersState(voiceConnection, VoiceConnectionStatus.READY, 5000);
        console.log(`Connected to ${channel.guild.name}`);
    } catch (err) {
        console.error(`Voice connection not ready within 30s: ${err}\n`);
    }

    player.play(resource);
    
    interaction.reply(`Successfully created a voice connection!\n`);
}

报错信息

Voice connection not ready within 30s: AbortError: The operation was aborted 
Unhandled Exception 
Error: DiscordAPIError[10062]: Unknown interaction 

(注:已将超时时间改为5000ms,但未修改错误提示中的30s)


解决方法

1. 修复交互超时问题

报错DiscordAPIError[10062]: Unknown interaction是因为Discord要求交互必须在3秒内回复,你的代码中等待语音连接就绪最多需要5秒,超出了限制导致交互过期。修改代码先延迟回复:

async execute(interaction) {
    const member = interaction.member;
    const channel = member.guild.channels.cache.get(interaction.channelId);

    if (channel.type !== ChannelType.GuildVoice) {
        return interaction.reply("只能在语音频道内调用/join命令。");
    }

    // 先发送延迟响应,避免交互超时
    await interaction.deferReply();

    const voiceConnection = joinVoiceChannel({
        channelId: channel.id,
        guildId: channel.guild.id,
        adapterCreator: channel.guild.voiceAdapterCreator,
        selfDeaf: false,
    });

    const player = createAudioPlayer();
    const resource = createAudioResource(__path);

    voiceConnection.subscribe(player);

    try {
        await entersState(voiceConnection, VoiceConnectionStatus.READY, 5000);
        console.log(`已连接到 ${channel.guild.name}`);
        player.play(resource);
        await interaction.editReply(`成功建立语音连接!\n`);
    } catch (err) {
        console.error(`语音连接未在5秒内就绪:${err}\n`);
        await interaction.editReply(`连接语音频道失败:${err.message}`);
    }
}

2. 验证音频文件路径

检查__path变量是否指向正确的本地音频文件,建议使用绝对路径测试,比如:

const resource = createAudioResource('/Users/xxx/Documents/audio.mp3');

3. 确保FFmpeg已安装

Discord.js的音频播放依赖FFmpeg,需确认环境中已安装并配置好:

  • Windows:下载FFmpeg并添加到系统PATH
  • macOS:执行brew install ffmpeg
  • Linux:执行sudo apt install ffmpeg

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

给音频播放器和语音连接添加错误监听,定位具体故障点:

player.on('error', error => {
    console.error(`播放器错误:${error.message}`);
});

voiceConnection.on('error', error => {
    console.error(`语音连接错误:${error.message}`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.04 01:13:10