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

Discord机器人无法播放yt-dlp获取的音频问题求助

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

排查FFmpeg核心问题

  • 先确认FFmpeg已加入系统PATH:Windows下把FFmpeg的bin目录(比如C:\ffmpeg\bin)添加到系统环境变量PATH,重启终端后输入ffmpeg -version验证是否能正常输出版本信息。如果没加PATH,直接在FFMPEG_OPTIONS里指定完整路径:
    FFMPEG_OPTIONS = {
        'executable': 'C:/ffmpeg/bin/ffmpeg.exe',
        'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
        'options': '-vn'
    }
    
  • 返回码1大多是参数错误,-vn参数必须加,用来禁用视频流,只保留音频;-reconnect系列参数是防止YouTube链接中途断开导致播放终止。

优化yt-dlp配置

  • 确保配置只拉取音频流,且无需本地保存:
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'opus',
            'preferredquality': '192',
        }],
        'quiet': True,
        'no_warnings': True,
        'default_search': 'ytsearch'
    }
    
    选择opus编码适配Discord语音频道,不要加outtmpl参数,避免强制生成本地文件。

修正Discord.py播放逻辑

  • 确保音频流正确传递,且播放完成后安全断开:
    async def play(ctx, url):
        if not ctx.author.voice:
            await ctx.send("你不在语音频道里!")
            return
        
        voice_channel = ctx.author.voice.channel
        voice_client = await voice_channel.connect()
    
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(url, download=False)
            audio_url = info['url']
    
        source = discord.FFmpegPCMAudio(audio_url, **FFMPEG_OPTIONS)
        # 播放完成后自动断开
        def after_play(error):
            if error:
                print(f"播放出错: {error}")
            asyncio.run_coroutine_threadsafe(voice_client.disconnect(), ctx.bot.loop)
    
        voice_client.play(source, after=after_play)
        # 等待播放结束
        while voice_client.is_playing():
            await asyncio.sleep(1)
    
    注意after回调要用线程安全方式调用断开,避免事件循环冲突;同时要等待播放完成,防止机器人提前退出语音频道。

其他排查项

  • 检查机器人权限:确保在目标语音频道有CONNECT和SPEAK权限。
  • 测试音频流可用性:从info['url']拿到音频链接后,用浏览器打开看是否能正常播放,排除网络或YouTube限制问题。
  • 更新依赖:执行pip install --upgrade discord.py[voice] yt-dlp确保所有库是最新版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:37