Playing music with a bot from Youtube without downloading the file

≡放荡痞女 提交于 2020-06-26 05:56:58

问题


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

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)

回答1:


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'} : 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


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:

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

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

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


来源:https://stackoverflow.com/questions/57688808/playing-music-with-a-bot-from-youtube-without-downloading-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!