我怎么去玩音乐使用不和谐机器人从YouTube没有下载歌曲作为文件?
我已经看过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={'格式':'最佳音频'}
:获取最佳音频youtube_dl. YoutubeDL(ydl_opts)作为ydl:
:初始化youtube-dlinfo=ydl.extract_info(video_link,下载=False)
:获取一个字典,名为info
,包含所有视频信息(标题、时长、上传者、描述…)URL=info['格式'][0]['url']
:获取视频的音频文件的URL语音=get(self.bot.voice_clients,公会=ctx. guild)
:初始化一个新的音频播放器voice.play(discord. FFmpegPCMAudio(URL))
:播放正确的音乐
但是,从URL播放音频而不下载会导致此处解释的已知问题
要修复它,只需添加一个变量,例如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))