gpt4 book ai didi

python-3.x - 在不下载文件的情况下使用 Youtube 的机器人播放音乐

转载 作者:行者123 更新时间:2023-12-04 12:42:02 24 4
gpt4 key购买 nike

如何在不将歌曲下载为文件的情况下使用 Youtube 的 discord bot 播放音乐?

我已经看过 discord.py 文档中包含的音乐机器人,但那个机器人会将文件下载到目录中。有什么办法可以避免这种情况吗?文档示例中的代码:

ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)

self.data = data

self.title = data.get('title')
self.url = data.get('url')

@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download= not stream))

if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]

filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


@client.command()
async def play(ctx, url):
voice = await ctx.author.voice.channel.connect()
player = await YTDLSource.from_url(url, loop=client.loop)
ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

最佳答案

要在不下载音乐的情况下播放音乐,只需将此代码用于您的 play 函数:

ydl_opts = {'format': 'bestaudio'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(video_link, download=False)
URL = info['formats'][0]['url']
voice = get(self.bot.voice_clients, guild=ctx.guild)
voice.play(discord.FFmpegPCMAudio(URL))

这是每行的用途:

  • ydl_opts = {'format': 'bestaudio'}:获得最好的音频
  • 将 youtube_dl.YoutubeDL(ydl_opts) 作为 ydl::初始化 youtube-dl
  • info = ydl.extract_info(video_link, download=False) : 获取一个名为 info 的字典,包含所有视频信息(标题、持续时间、上传者、描述, ...)
  • URL = info['formats'][0]['url'] : 获取指向视频音频文件的 URL
  • voice = get(self.bot.voice_clients, guild=ctx.guild):初始化一个新的音频播放器
  • voice.play(discord.FFmpegPCMAudio(URL)):播放正确的音乐


但是,从 URL 播放音频而不下载它会导致已知问题的解释 here
要修复它,只需添加一个变量,例如 FFMPEG_OPTIONS,它将包含 FFMPEG 的选项:

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

创建变量后,只需向 FFmpegPCMAudio 方法添加一个参数:

voice.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))

关于python-3.x - 在不下载文件的情况下使用 Youtube 的机器人播放音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57688808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com