3

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)
2
  • You can't play something without downloading its bytes. It's impossible.
    – Daniel W.
    Commented Mar 23, 2021 at 12:54
  • I guess you just want to download without persisting the bytes but still you first need to download.
    – Daniel W.
    Commented Mar 23, 2021 at 12:57

1 Answer 1

5

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:

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 the FFmpegPCMAudio method:

voice.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
2
  • This is still downloading the bytes from youtube. You can't send/play something you don't have. Playing without downloading is impossible.
    – Daniel W.
    Commented Mar 23, 2021 at 12:55
  • The function discord.FFmpegPCMAudio() is downloading the bytes through ffmpeg.
    – Daniel W.
    Commented Mar 23, 2021 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.