Search code examples
pythonffmpegdiscord.pyyoutube-dl

Is it possible to seek through streamed youtube audio with discord.py (play from a given timestamp in the video)?


Unfortunately passing in a URL with a &t= tag does not cause discord.py's VoiceClient to start playing at that timestamp. I'm using youtube_dl.

Is is possible to seek through audio within discord.py in order to start streaming a YouTube video from somewhere besides the start?

I know some professional bots like Groovy have seek commands for streamed YouTube videos, so the Discord API itself is capable of this.

The code I'm using is from here.


Solution

  • In the ffmpeg_options, you're able to seek to a specific timestamp with the use of the -ss flag.

    This is just how the options should look if you wish to start from, for example, 40 seconds:

    ffmpeg_options = {
        'options': '-vn -ss 40'
    }
    

    And of course you can add an optional variable to the stream command:

    import typing # for the optional argument of the timestamp
    
        @classmethod
        async def from_url(cls, url, *, loop=None, stream=False, timestamp=0):
            # moved the options from outside the class to inside the method.
            # this allows the use of variables in the options
            ffmpeg_options = {
                'options': f'-vn -ss {timestamp}'
            }
            # rest of the from_url code
    
        @commands.command()
        async def stream(self, ctx, timestamp: typing.Optional[int]=0, *, url): # add the arg
            """Streams from a url (same as yt, but doesn't predownload)"""
    
            async with ctx.typing():
                player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True, timestamp=timestamp)
                # other code
    

    I only added in the code that I edited from the music bot example, so I hope it's clear what I edited. If any further clarification is needed/how something works, then I'll be happy to make edits.


    References: