使用YouTube上的机器人播放音乐而无需下载文件 [英] Playing music with a bot from Youtube without downloading the file

查看:160
本文介绍了使用YouTube上的机器人播放音乐而无需下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不将歌曲下载为文件的情况下,如何使用Youtube上的不和谐机器人播放音乐?

How would i go about playing music using a discord bot from Youtube without downloading the song as a file?

我已经看过其中包含的音乐bot在discord.py文档中,但是该bot将文件下载到目录中。有什么办法可以避免这种情况?文档示例中的代码:

I've already had a look at the included music bot in the discord.py documentation but that one downloads a file to the directory. Is there any way to avoid this? Code from the documentation example:

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)


推荐答案

下载它,只需在您的播放功能中使用此代码n:

To play music without downloading it, simply use this code into your play function :

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))

这是每行的用途:

Here is what each line is used for :


  • ydl_opts = {'format':'bestaudio'} :使用youtube_dl获得最佳音频

  • 。YoutubeDL(ydl_opts)为ydl::初始化youtube -dl

  • info = ydl.extract_info(video_link,download = False):获取一本名为<$ c的字典$ c> info ,包含所有视频信息(标题,时长,上传者,说明等)。

  • URL = info ['formats'] [0] ['url'] :获取指向视频音频文件的URL

  • voice = get(self.bot.voice _clients,guild = ctx.guild):初始化一个新的音频播放器

  • voice.play(discord.FFmpegPCMAudio(URL) )):播放正确的音乐

  • ydl_opts = {'format': 'bestaudio'} : get the best possible audio
  • with youtube_dl.YoutubeDL(ydl_opts) as ydl: : initialize youtube-dl
  • info = ydl.extract_info(video_link, download=False) : get a dictionary, named info, containing all the video information (title, duration, uploader, description, ...)
  • URL = info['formats'][0]['url'] : get the URL which leads to the audio file of the video
  • voice = get(self.bot.voice_clients, guild=ctx.guild) : initialize a new audio player
  • voice.play(discord.FFmpegPCMAudio(URL)) : play the right music


但是,从URL播放音频而不下载会导致已知问题解释 此处

要对其进行修复,只需添加一个变量,例如 FFMPEG_OPTIONS 其中将包含FFMPEG的选项:


However, Playing audio from an URL without downloading it causes a known issue explained here
To fix it, just add a variable, for instance, FFMPEG_OPTIONS which will contain options for FFMPEG:

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

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

Once you've created the variable, you just have to add one argument to the FFmpegPCMAudio method:

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

这篇关于使用YouTube上的机器人播放音乐而无需下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆