如何为Discord.py机器人实现音乐流媒体播放 无需每次下载文件
要实现无需下载的YouTube音频流播放,无需更换现有FFMPEG、youtube_dl工具链,仅需调整配置和代码逻辑即可,修改方案如下:
1. 调整youtube_dl初始化配置
新增流提取相关参数,不需要将文件下载到本地:
ytdl_format_options = { 'format': 'bestaudio/best', 'restrictfilenames': True, 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0', # 以下为流播放核心配置 'extractaudio': True, 'audioformat': 'mp3', 'dump_single_json': True, }
2. 修正后的play命令完整代码
@bot.command(name='play', help='播放YouTube视频音频') async def play(ctx, *, url): try: # 获取当前机器人已连接的语音客户端实例 voice_client = ctx.guild.voice_client # 若未连接语音频道,自动加入触发命令用户所在的频道 if not voice_client or not voice_client.is_connected(): if not ctx.author.voice: await ctx.send("你需要先加入一个语音频道") return voice_client = await ctx.author.voice.channel.connect() await ctx.send('正在尝试加载资源...') async with ctx.typing(): # 传入stream=True参数,直接提取音频流地址无需下载 audio_source = await YTDLSource.from_url(url, loop=bot.loop, stream=True) voice_client.play(discord.FFmpegPCMAudio( source=audio_source.url, executable="ffmpeg.exe", # 新增断连重试参数,避免播放中途卡顿 before_options="-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5" )) await ctx.send(f'**当前播放:** {audio_source.title}') except: await ctx.send("未连接到语音频道或当前已有内容正在播放")
额外优化建议
如果youtube_dl提取流地址失败率高,可以直接替换为功能兼容的yt-dlp,无需修改现有调用逻辑,对新YouTube视频的适配性更好。
内容的提问来源于stack exchange,提问作者Happy Lama
相关产品推荐
相关产品推荐

