Python中使用ffmpeg转音频为mp3实现32位设备Discord机器人语音播放
32位设备下Discord机器人FFmpeg音频转码播放实现方案
前置依赖配置
- 安装适配32位系统的FFmpeg稳定版,完成后执行
ffmpeg -version确认系统可正常识别该命令,若未识别可手动将FFmpeg所在目录加入系统环境变量,或在代码中指定FFmpeg可执行文件路径 - 安装Python依赖:
pydub为FFmpeg的封装工具,可简化音频转码逻辑开发。pip install discord.py pydub
核心功能实现
原代码仅支持固定本地MP3文件播放,修改后新增任意音频转MP3逻辑,适配动态知识库音频片段播放需求:
import discord from discord.ext import commands import os from pydub import AudioSegment import tempfile client = commands.Bot(command_prefix="!") @client.command() async def play(ctx, audio_path: str): print('We have logged in as {0.user}'.format(client)) # 检查是否已连接语音频道 voice = discord.utils.get(client.voice_clients, guild=ctx.guild) if not voice: voiceChannel = discord.utils.get(ctx.guild.voice_channels, name="Lounge") voice = await voiceChannel.connect() # 转码逻辑:支持任意输入格式转MP3 try: # 读取输入音频,可兼容本地路径、远程直链 audio = AudioSegment.from_file(audio_path) # 生成临时MP3文件,转码后调用 temp_file = tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) audio.export(temp_file.name, format="mp3") temp_file.close() # 32位设备适配:如果FFmpeg未加入环境变量,新增executable参数指定32位FFmpeg完整路径 # 示例:executable="C:/ffmpeg_x86/ffmpeg.exe" voice.play(discord.FFmpegPCMAudio(temp_file.name), after=lambda e: os.remove(temp_file.name)) except Exception as e: await ctx.send(f"音频处理失败:{str(e)}") @client.command() async def ext(ctx): voice = discord.utils.get(client.voice_clients, guild=ctx.guild) if voice: await voice.disconnect() client.run('你的机器人token')
使用说明
- 调用指令格式为
!play 音频路径,音频路径支持本地文件路径、音频文件直链地址 - 转码生成的临时文件会在播放完成后自动删除,避免占用磁盘空间
- 动态知识库场景下可提前缓存高频调用的音频转码结果,减少重复转码的性能消耗
- 32位系统下建议使用3.x版本的32位FFmpeg编译包,避免高版本FFmpeg的兼容性报错
内容的提问来源于stack exchange,提问作者user15082770
相关产品推荐
相关产品推荐

