Discord机器人FFmpeg无音频输出,执行卡在语音连接阶段
Discord机器人!play命令连接语音后无后续执行及音频输出问题排查
问题现象
调用!play命令时,机器人成功完成语音握手并连接到语音频道,但后续代码未执行(未打印trying1),完全没有音频输出。已尝试设置FFmpeg的executable参数和调试,问题仍未解决。
用户提供代码
import discord from discord.ext import commands import asyncio intents = discord.Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.event async def on_ready(): print(f'Logged in as {bot.user.name}') @bot.command() async def play(ctx): if ctx.author.voice is None: await ctx.send("You need to be in a voice channel to use this command.") return channel = ctx.author.voice.channel voice_client = await channel.connect() print('trying1') try: print('trying2') source = discord.FFmpegPCMAudio("zzzz.mp3") voice_client.play(source) print('trying3') except Exception as e: print(f"An error occurred while playing the music: {e}") print('trying')
日志输出
[2023-06-25 02:30:01] [INFO ] discord.voice_client: Connecting to voice... [2023-06-25 02:30:01] [INFO ] discord.voice_client: Starting voice handshake... (connection attempt 1) [2023-06-25 02:30:01] [INFO ] discord.voice_client: Voice handshake complete. Endpoint found russia5225.discord.media
故障原因及解决方法
1. channel.connect()未捕获异常导致代码中断
await channel.connect()遇到机器人已在目标语音频道、连接超时或权限问题时,会抛出discord.ClientException异常,但原代码未对该操作做异常处理,异常直接终止函数执行,后续代码无法运行。
解决方式:给connect()添加异常捕获逻辑,同时处理已连接的情况:
try: voice_client = await channel.connect() except discord.ClientException as e: print(f"Connection error: {e}") # 若已连接,获取现有语音客户端 voice_client = ctx.voice_client if voice_client is None: await ctx.send("无法连接到语音频道") return
2. FFmpeg路径未正确配置或文件不存在
原代码未指定FFmpeg可执行文件路径,若系统环境变量未配置FFmpeg,会导致FFmpegPCMAudio初始化失败;同时需确保zzzz.mp3文件与脚本在同一目录,或使用绝对路径。
解决方式:
- 显式指定FFmpeg路径:
# Windows示例 source = discord.FFmpegPCMAudio("zzzz.mp3", executable="C:/ffmpeg/bin/ffmpeg.exe") # Linux/macOS示例 # source = discord.FFmpegPCMAudio("zzzz.mp3", executable="/usr/bin/ffmpeg") - 确认音频文件路径正确,可使用绝对路径避免路径问题:
import os audio_path = os.path.join(os.path.dirname(__file__), "zzzz.mp3") source = discord.FFmpegPCMAudio(audio_path, executable="你的FFmpeg路径")
3. Discord.py版本或依赖缺失
语音功能需要discord.py的voice扩展依赖,若版本过旧或未安装依赖会导致功能异常。
解决方式:更新discord.py并安装语音依赖:
pip install -U discord.py[voice]
4. 语音客户端状态异常
即使连接成功,语音客户端可能处于未就绪状态,可添加状态检查:
if not voice_client.is_connected(): await ctx.send("语音客户端未成功连接") return
内容的提问来源于stack exchange,提问作者koya
相关产品推荐
相关产品推荐

