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

DiscordJS v13 AudioPlayer播放YouTube音频时卡在buffering状态问题

问题根因

ytdl返回的音频流格式、参数配置不匹配@discordjs/voice的播放器要求,加上缺失错误监听导致无法感知底层故障,是卡住buffering状态的核心原因。

修复步骤
  • 补充@discordjs/voice必选依赖:确保已经安装@discordjs/opus/opusscript、ffmpeg-static、prism-media三个依赖,缺一不可。
  • 调整ytdl拉流参数,指定兼容Discord的音频格式
  • 给AudioPlayer和音频流添加错误监听,捕获底层故障
  • 显式指定音频资源的输入类型,减少播放器转码判断耗时
修正后代码
// 头部先导入需要的类型
const { StreamType } = require('@discordjs/voice');

client.on("messageCreate", async message => {
    if (message.content.slice(0, 6) == "!play ") {
        let input = message.content.slice(6);
        let url;
        if (isYoutubeUrl(input)) {
            url = input;
        } else {
            const searchTerm = formatInput(input);
            url = await searchVideo(searchTerm);
        }
        if (message.member.voice.channelId !== null) {
            const permissions = message.member.voice.channel.permissionsFor(message.client.user);
            if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
              return message.channel.send(
                "I need the permissions to join and speak in your voice channel!"
              );
            }

            const connection = joinVoiceChannel({
                channelId: message.member.voice.channel.id,
                guildId: message.guild.id,
                adapterCreator: message.guild.voiceAdapterCreator
            })

            // 调整ytdl参数
            const stream = ytdl(url, { 
                filter:'audioonly',
                quality: 'highestaudio',
                highWaterMark: 1 << 25 // 32MB缓冲,减少网络波动影响
            });

            // 监听流错误
            stream.on('error', err => {
                console.error('拉流错误:', err);
                message.channel.send('音频加载失败,请尝试其他视频');
            })
        
            const player = createAudioPlayer();
            // 显式指定流类型为OggOpus,跳过播放器自动检测
            var resource = createAudioResource(stream, { 
                seek: 0, 
                volume: 1,
                inputType: StreamType.OggOpus
            });

            // 添加播放器事件监听
            player.on('error', err => {
                console.error('播放器错误:', err);
                message.channel.send('播放出错');
            })
            player.on('stateChange', (oldState, newState) => {
                console.log(`播放器状态从 ${oldState.status} 切换到 ${newState.status}`);
            })

            player.play(resource);
            connection.subscribe(player);

        } else {
            message.reply("You need to be in a voice channel to play music!");
        }
    }
})
额外排查点

如果修改后仍然卡住,检查ytdl-core版本是否为最新,YouTube定期会更新接口,旧版本ytdl-core会出现拉流异常,直接升级到最新版本即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:57:02