Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

python 3.x - Playing music with a bot from Youtube without downloading the file

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...