来自MP3 url的discord.py流音频

2024-05-15 11:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python3中有一个使用Discord.py的Discord机器人,我想让它将来自欧洲学校广播的音频流传输到语音聊天。这是我目前拥有的代码:

@bot.command(name='esr')
async def esr(ctx):
    ffmpeg_options = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn'}

    guild = ctx.guild

    channel = discord.utils.get(guild.voice_channels, name='ESR') # Always connects to a channel named ESR

    voice_client = discord.utils.get(bot.voice_clients, guild=guild)

    if voice_client is None:
        voice_client = await channel.connect()
    else:
        await voice_client.move_to(channel)


    try:
        url = 'http://europeanschoolradio.eu:1351/esradio.mp3'
        esr = pafy.new(url)

        audio = esr.getbestaudio()

        source = discord.FFmpegPCMAudio(audio.url, **ffmpeg_options)

        voice_client.play(source)  # play the source
    except discord.ClientException as e:
        await ctx.send(f"A client exception occured:\n`{e}`")
    except TypeError as e:
        await ctx.send(f"TypeError exception:\n`{e}`")
    except discord.opus.OpusNotLoaded as e:
        await ctx.send(f"OpusNotLoaded exception: \n`{e}`")

然而,它没有工作,并抛出了一个例外,它需要一个11个字符的视频ID或URL,从中我意识到pafy是视频,而不是音频。我试着看这里,只看到了pafy的一个解决方案,但它是一个带有视频的YouTube URL,而不是像我这样的音频。在不下载音频的情况下,我可以做些什么来流式传输音频?感谢所有的帮助。谢谢大家!


Tags: clienturlsourcechannelawait音频optionsctx