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

如何解决Python+Spotipy开发Discord机器人的‘ffmpeg was not found’错误

Discord机器人播放Spotify歌曲问题解决方案

一、解决FFmpeg未找到错误

discord.py依赖FFmpeg处理音频流,当前报错核心是系统未安装FFmpeg或路径未配置:

  • macOS安装方式:通过Homebrew执行 brew install ffmpeg;若未安装Homebrew,先安装Homebrew再执行该命令。
  • 验证安装:终端输入 ffmpeg -version,能正常输出版本信息即为安装成功。
  • 指定路径(可选):若安装后仍报错,可在代码中手动指定FFmpeg路径,路径可通过 which ffmpeg 命令查询:
    discord.FFmpegPCMAudio(track_preview_url, executable="/usr/local/bin/ffmpeg")
    

二、纠正Spotify音频链接获取逻辑

你当前代码获取的是专辑网页链接,并非可播放的音频预览链接,需修改为:

track_preview_url = track_info.get('preview_url')

preview_url是Spotify提供的30秒歌曲预览音频链接,注意部分歌曲无此链接,需增加空值判断。

三、优化完整播放逻辑

补充用户状态检查、语音连接复用、异常处理等逻辑,避免重复连接或无意义报错:

@client.command()
async def play(ctx, track_url):
    # 检查用户是否在语音频道
    if not ctx.author.voice:
        await ctx.send("请先加入一个语音频道!")
        return
    
    voice_channel = ctx.author.voice.channel
    voice_client = ctx.voice_client

    # 处理语音连接:未连接则连接,已连接则切换频道
    if not voice_client:
        voice_client = await voice_channel.connect()
    elif voice_client.channel != voice_channel:
        await voice_client.move_to(voice_channel)
    
    try:
        track_info = spotify.track(track_url)
        track_preview_url = track_info.get('preview_url')
        
        if not track_preview_url:
            await ctx.send("该歌曲无可用预览音频!")
            return
        
        # 初始化音频源(可根据需要指定FFmpeg路径)
        audio_source = discord.FFmpegPCMAudio(track_preview_url)
        voice_client.play(audio_source)
        await ctx.send(f"正在播放:{track_info['name']} - {track_info['artists'][0]['name']}")
    except Exception as e:
        await ctx.send(f"播放失败:{str(e)}")
        # 出错后断开语音连接(可选)
        if voice_client.is_connected():
            await voice_client.disconnect()

四、版权与功能限制说明

Spotify官方仅允许播放30秒预览音频,若需完整播放歌曲,涉及版权合规问题,无法直接通过Spotipy抓取完整音频。若需实现完整播放,需通过用户Spotify账户授权(使用Spotipy的OAuth2授权流程),或采用符合版权要求的第三方方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:33:29