【问题标题】:How can I make my bot play audio faster? (discord.py rewrite)如何让我的机器人更快地播放音频? (discord.py 重写)
【发布时间】:2021-08-16 18:25:01
【问题描述】:

我的音乐大约需要 30 秒或更长时间才能开始播放音频,我想知道是否有任何方法可以让它像 Groovy 和许多其他机器人一样更快地播放音频。对此的所有帮助表示赞赏。我知道直接从 yt 流式传输是一回事,我的机器人目前下载并提取文件,然后播放它。这是我的代码:

@bot.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, url: str):
    global voice
    channel = ctx.message.author.voice.channel
    voice = get(bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    await voice.disconnect()

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
        print(f"The bot has connected to {channel}\n")

    def check_queue():
        Queue_infile = os.path.isdir("./Queue")
        if Queue_infile is True:
            DIR = os.path.abspath(os.path.realpath("Queue"))
            length = len(os.listdir(DIR))
            still_q = length - 1
            try:
                first_file = os.listdir(DIR)[0]
            except:
                print("No more queued song(s)\n")
                queues.clear()
                return
            main_location = os.path.dirname(os.path.realpath(__file__))
            song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
            if length != 0:
                print("Song done, playing next queued\n")
                print(f"Songs still in queue: {still_q}")
                song_there = os.path.isfile("song.mp3")
                if song_there:
                    os.remove("song.mp3")
                shutil.move(song_path, main_location)
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, 'song.mp3')

                voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
                voice.source = discord.PCMVolumeTransformer(voice.source)
                voice.source.volume = 0.07

            else:
                queues.clear()
                return

        else:
            queues.clear()
            print("No songs were queued before the ending of the last song\n")

【问题讨论】:

  • 也许Code Review Stack Exchange 是一个更好的地方。
  • Code Review 发帖之前,请务必阅读A guide to Code Review for Stack Overflow users,因为那里有些事情的处理方式不同 - 例如。问题标题应该简单地说明代码做了什么,因为问题总是“我该如何改进?”。确保代码正常工作;如果可能的话,包括你的单元测试。您可能会收到一些建议,使其更高效、更易于阅读和更好地测试。

标签: python discord.py


【解决方案1】:

我不确定是什么原因导致它变慢,但我认为这可能与您的 pc/host 服务的互联网连接有关,我认为您应该尝试直接从 youtube 流式传输以使其更快


queue = []

YDL_OPTIONS = = {
            "format" : "bestaudio",
            "postprocessors" : [{
                "key" : "FFmpegExtractAudio",
                "preferredcodec" : "mp3",
                "preferredquality" : "192",
            }], "noplaylist" : "True"
        }

FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

def play_next():
    queue.pop(0)
    if len(queue) >= 1:
        source = queue[0]['source']
        voice.play(discord.FFmpegPCMAudio(queue[0]['source'], FFMPEG_OPTIONS), after=lambda e: play_next())
        voice.source = discord.PCMVolumeTransformer(voice.source)
        voice.source.volume = 0.07

def lstr(list : Iterable):
        string = f"{list[0]}"
        for i in range(1, len(list)):
            string += f" {list[i]}"
        return string

def search_yt(item):
        with YoutubeDL(YDL_OPTIONS) as ydl:
            try: 
                info = ydl.extract_info("ytsearch:%s" % item, download=False)['entries'][0]
            except Exception: 
                return False

        return {'source': info['formats'][0]['url'], 'title': info['title']}

@bot.command(pass_context=True, aliases=['p', 'pla'])
async def play(ctx, *query):
    query = lstr(query)
    song = search_yt(query)
    queue.append[song]
    global voice
    channel = ctx.message.author.voice.channel
    voice = get(bot.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()

    await voice.disconnect()

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
        print(f"The bot has connected to {channel}\n")

    voice.play(discord.FFmpegPCMAudio(queue[0]['source'], FFMPEG_OPTIONS), after=lambda e: play_next())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.07

或者你可以找一个主机,这样会更快一点;)

【讨论】:

  • 这个流代码不起作用,它说Iterable is not defined
  • 尝试导入Iterable
猜你喜欢
  • 2019-05-05
  • 2021-05-05
  • 2021-09-17
  • 2020-08-30
  • 2021-10-01
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多