discord.py音乐机器人用youtube_dl遇ffprobe错误:webm转mp3失败
问题解决:Discord音乐机器人webm转mp3失败(ffprobe无法获取音频编码)
问题原因
这个报错核心是youtube-dl调用ffprobe识别下载的webm文件时失败,常见触发原因有两个:
- FFmpeg未正确安装或未添加到系统环境变量,导致youtube-dl找不到ffprobe工具
- youtube-dl的转码配置不完善,或下载的webm采用特殊编码,默认转码逻辑无法识别
修复步骤
第一步:检查FFmpeg环境
- 下载对应系统版本的FFmpeg(自带ffprobe工具)并完成安装
- 将FFmpeg安装目录下的
bin文件夹路径添加到系统环境变量PATH中 - 打开命令提示符输入
ffprobe -version,能正常输出版本信息则说明配置成功
第二步:代码修复方案(二选一)
方案一:优化youtube-dl配置
修改原代码中的ydl_opts,明确指定ffmpeg路径(环境变量未配置时)并调整格式参数:
ydl_opts = { 'format': 'bestaudio[ext=webm]/bestaudio', # 优先选择webm格式音频 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'ffmpeg_location': 'C:/path/to/ffmpeg/bin/ffmpeg.exe', # 替换为你的FFmpeg实际路径,Windows需用斜杠或双反斜杠 'noplaylist': True, # 避免误下载播放列表 'quiet': True, # 减少冗余日志输出 }
同时补充文件清理逻辑,避免残留原webm文件和重命名冲突:
with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) webm_file = ydl.prepare_filename(info) # 获取下载的原webm文件名 # 重命名mp3并清理原文件 for file in os.listdir("./"): if file.endswith(".mp3"): if os.path.exists("song.mp3"): os.remove("song.mp3") os.rename(file, "song.mp3") # 删除原webm文件 if os.path.exists(webm_file): os.remove(webm_file)
方案二:手动调用FFmpeg转码(更稳定)
绕过youtube-dl的内置转码逻辑,先下载webm再直接用subprocess调用ffmpeg转码,可控性更强:
@client.command() async def play(ctx, url: str): # 连接语音频道逻辑 voice_channel = discord.utils.get(ctx.guild.voice_channels, name='General') await voice_channel.connect() voice_client = discord.utils.get(client.voice_clients, guild=ctx.guild) # 下载webm临时文件 ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'temp.webm', # 指定临时文件名 'noplaylist': True, 'quiet': True, } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) # 调用FFmpeg转码为mp3 import subprocess subprocess.run([ 'ffmpeg', '-i', 'temp.webm', '-vn', '-acodec', 'libmp3lame', '-ab', '192k', 'song.mp3', '-y' # 强制覆盖已有文件 ], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 删除临时webm文件 os.remove("temp.webm") voice_client.play(discord.FFmpegPCMAudio("song.mp3"))
额外注意事项
- 确保机器人拥有目录的读写权限,避免出现文件删除/重命名的权限错误
- 可补充语音频道连接判断,避免重复连接同一频道
- 可在音频播放完成后自动删除
song.mp3,避免后续播放冲突
内容的提问来源于stack exchange,提问作者Inactive Gaming13
相关产品推荐
相关产品推荐

