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

如何让Discord音乐机器人边加载边播放以提升运行速度?

实现Discord音乐机器人边加载边播放的方案

你当前的代码是先把音频完整下载到本地文件,再启动播放,所以必须等整个下载流程完成(10秒左右)才能开始播放。用asyncio.run_in_executor只是把下载放到后台线程,不阻塞机器人的事件循环,但还是要等下载结束才会创建音频源并播放,所以启动速度没明显提升。

要实现边加载边播放,核心思路是直接获取音频的流媒体URL,让FFmpeg从网络流读取数据并实时播放,不用先把整个文件下载到本地。下面是修改后的完整代码:

import discord
from discord.ext import commands
import yt_dlp
import time
import asyncio

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
current_speed = 1.0

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}!')

@bot.command(name="play")
async def play(ctx, url: str):
    start_time = time.time()
    global current_speed

    if not ctx.voice_client:
        if ctx.author.voice:
            channel = ctx.author.voice.channel
            message = await ctx.send("Loading music...")
            await channel.connect()
        else:
            await ctx.send("You're not in a voice channel!")
            return
    else:
        await ctx.voice_client.move_to(ctx.author.voice.channel)

    ffmpeg_path = "./ffmpeg/ffmpeg.exe"

    # 修改yt-dlp配置:只获取音频流URL,不下载文件
    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,  # 关闭多余输出
        'no_warnings': True,
        'ffmpeg_location': ffmpeg_path
    }

    # 获取音频流信息,提取直接播放的URL
    loop = asyncio.get_event_loop()
    info = await loop.run_in_executor(None, lambda: yt_dlp.YoutubeDL(ydl_opts).extract_info(url, download=False))
    audio_url = info['url']

    # 用流媒体URL创建音频源,添加ffmpeg选项处理流播放
    audio_source = discord.FFmpegPCMAudio(
        executable=ffmpeg_path,
        source=audio_url,
        options=f"-re -filter:a 'atempo={current_speed}' -vn"
    )

    if not ctx.voice_client.is_playing():
        ctx.voice_client.play(audio_source)
        await message.edit(content=f"Started playing!")
    else:
        await ctx.send("The bot is currently playing another sound.")

    end_time = time.time()
    elapsed_time = end_time - start_time
    await ctx.send(f"Play command completed in {elapsed_time:.2f} seconds.")

bot.run("BOT_TOKEN")

关键改动说明:

  • 去掉本地下载相关配置:删除了postprocessors、outtmpl,因为不需要把音频保存到本地文件了。
  • 改用extract_info获取流URL:通过download=False参数让yt-dlp只解析视频信息,不下载,直接提取音频的流媒体地址info['url']。
  • FFmpeg流播放选项:添加-re参数让FFmpeg以实时速度读取流,避免一次性缓冲过多;-vn参数忽略视频流(只处理音频),减少资源占用。
  • 移除本地文件操作:不需要再创建和删除music.mp3,简化流程。

这样修改后,机器人会在获取到流媒体URL后立刻启动播放,不需要等整个音频下载完成,启动耗时会从原来的10秒左右大幅缩短到1-2秒,实现边加载边播放的效果。

内容的提问来源于stack exchange,提问作者Aktuğ İ.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:22:01