Discord Python机器人FFmpegPCMAudio无法播放音频问题咨询
问题排查与修复方案
一、代码本身的潜在问题
- 重复连接语音频道:每次执行
$outro都会调用await channel.connect(),如果机器人已经在频道内,会引发连接冲突。应该先检查连接状态再决定是否连接。 - 异步调用遗漏
await:esci命令的else分支里,ctx.send('not in a voice chat')没加await,会触发报错并影响后续逻辑执行。 - 冗余代码无效:
bot.get_command('outro')和bot.get_command('esci')这两行完全没用,直接删掉即可。
修复后的完整代码:
import discord as ds from discord.ext import commands from discord import FFmpegPCMAudio intents = ds.Intents.all() bot = commands.Bot(command_prefix='$', intents=intents) @bot.event async def on_ready(): print('bot online.') @bot.command(pass_context=True) async def outro(ctx): if ctx.author.voice: # 先检查是否已在语音频道,避免重复连接 if ctx.voice_client is None: voce = await ctx.author.voice.channel.connect() else: voce = ctx.voice_client # 停止当前播放的音频,避免冲突 if voce.is_playing(): voce.stop() source = FFmpegPCMAudio('outro.mp3') player = voce.play(source) else: await ctx.send('not in a voice chat') @bot.command(pass_context=True) async def esci(ctx): if ctx.voice_client: await ctx.guild.voice_client.disconnect() await ctx.send('adios @everyone') else: # 补上await关键字 await ctx.send('not in a voice chat') bot.run('你的Bot令牌')
二、FFmpeg相关问题
- 指定FFmpeg可执行文件路径:如果系统无法自动找到FFmpeg,需要手动指定完整路径。比如Windows环境:
Linux/macOS环境确保FFmpeg已安装,或指定路径:source = FFmpegPCMAudio('outro.mp3', executable='C:/ffmpeg/bin/ffmpeg.exe')source = FFmpegPCMAudio('outro.mp3', executable='/usr/bin/ffmpeg') - 检查音频文件状态:确认
outro.mp3没有损坏,路径是否正确(可以尝试用绝对路径测试),或者文件权限是否被系统更新等操作修改。 - FFmpeg版本兼容性:如果FFmpeg自动更新后出现问题,回退到之前的稳定版本,或重新安装最新官方稳定版。
三、依赖与权限问题
- 更新discord.py语音依赖:确保安装带语音支持的discord.py版本,执行更新命令:
pip install --upgrade discord.py[voice] - 确认机器人权限:检查机器人在服务器内是否拥有「连接语音频道」和「播放语音」的权限,避免权限被误修改导致无法播放。
内容的提问来源于stack exchange,提问作者user1010
相关产品推荐
相关产品推荐

