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

使用pydub搭配discord.py开发机器人无音频输出无报错如何解决

问题排查与解决步骤
  • 核心逻辑错误修正:你当前代码的首要问题是错误传递了AudioSegment对象给FFmpegPCMAudio。AudioSegment.from_file()返回的是pydub的音频段对象,直接转str()得到的是对象的描述文本,既不是音频数据也不是文件路径,FFmpeg无法正常读取,自然不会输出音频。
  • FFmpeg配置验证:首先确认FFmpeg已正确配置,若未加入系统环境变量,executable='ffmpeg'无法定位程序,需要写全FFmpeg的绝对路径,比如executable='C:\\ffmpeg\\bin\\ffmpeg.exe'。可以先在CMD中运行ffmpeg -version验证是否能正常调用。
  • 权限与连接检查:确认Discord机器人拥有对应语音频道的连接、发言权限,同时确认你和机器人处于同一个语音频道。
  • 错误回调添加:可以给play方法增加错误回调,捕获播放过程中隐藏的报错:
def after_play(error):
    if error:
        print(f"播放出错:{error}")

调用播放时传入after=after_play即可。

修正后代码示例

无需pydub处理的最简版本

如果不需要对音频做剪辑、调速等处理,直接传文件路径即可,无需引入pydub:

@bot.command(name='playtest', case_insensitive=True) 
async def voice(context):
    # 校验用户是否在语音频道
    if not context.author.voice:
        await context.send("你需要先加入一个语音频道")
        return
    channel = context.author.voice.channel
    # 避免重复连接报错
    if context.voice_client:
        await context.voice_client.move_to(channel)
    else:
        await channel.connect()
    voice_client = context.voice_client
    audio_path = 'C:\\Users\\ryanc\\Music\\lofibot project\\nuver\\nuver_piano.wav'
    voice_client.play(discord.FFmpegPCMAudio(audio_path, executable='ffmpeg'), after=lambda e: print(f"播放错误: {e}") if e else None)
    await context.send("正在播放音频")

需要pydub处理音频的版本

如果需要用pydub做音量调整、片段剪辑等操作,需要将处理后的音频导出为字节流再传给FFmpeg:

from pydub import AudioSegment
import io

@bot.command(name='playtest', case_insensitive=True) 
async def voice(context):
    if not context.author.voice:
        await context.send("你需要先加入一个语音频道")
        return
    channel = context.author.voice.channel
    if context.voice_client:
        await context.voice_client.move_to(channel)
    else:
        await channel.connect()
    voice_client = context.voice_client
    audio_path = 'C:\\Users\\ryanc\\Music\\lofibot project\\nuver\\nuver_piano.wav'
    # 加载并处理音频
    sound = AudioSegment.from_file(audio_path)
    # 此处可添加自定义处理逻辑,例如 sound = sound + 6 代表音量提升6dB
    # 导出为字节流
    buffer = io.BytesIO()
    sound.export(buffer, format='wav')
    buffer.seek(0)
    # 传入字节流需要开启pipe模式
    voice_client.play(discord.FFmpegPCMAudio(buffer, pipe=True, executable='ffmpeg'), after=lambda e: print(f"播放错误: {e}") if e else None)
    await context.send("正在播放处理后的音频")

内容的提问来源于stack exchange,提问作者sunatdoc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:51:00