Discord.py - 将 Youtube 直播转化为语音

SUP*_*500 3 youtube ffmpeg python-3.x discord.py

我又回到了书库,被禁止提问,因为它们显然很糟糕,但我需要一些帮助,我已经做了很多研究,但找不到答案;

\n

我需要能够使用discord.py Rewrite 将 youtube 直播的音频流式传输到 VC 中以播放广播音乐。我一直在查看 Youtube_DL 和/或 FFMpeg 相关的互联网帖子,所有帖子要么已经过时(discord.py==0.16.x),要么涉及下载 YouTube 视频(无法通过持续的流来执行此操作)。

\n

我还尝试查看discord.py v0.16.12 voice_client.pycreate_ytdl_player。但无济于事,我找不到任何解决方案。

\n

这是我的代码目前的情况。这是我的一个齿轮中的一项后台任务。

\n
    @loop(seconds=5)\n    async def check_voice(self):\n        try:\n            channel = await self.bot.fetch_channel(819346920082112532)\n        except NotFound:\n            print("[IR] `Infinite Lofi` voice channel not found. Stopping check_voice loop.")\n            self.check_voice.cancel()\n            return\n\n        try:\n            infinite_lofi = await channel.connect(timeout=2, reconnect=True)\n        except ClientException:\n            return\n        else:\n            print("[IR] Connected to voice channel.  Loading from config livestream URL...")\n            channel = await self.bot.fetch_channel(780849795572826213)\n            message = await channel.fetch_message(780859270010503188)\n            ctx = await self.bot.get_context(message)\n\n            # infinite_lofi.play()  <<< Looking to play a youtube live stream audio.\n
Run Code Online (Sandbox Code Playgroud)\n

根据discord.py 文档,我需要一个 AudioSource 来传递到VoiceClient.play().
\n我的目标是播放现场音频,而不是下载。换句话说,流。
\n如果您需要一个示例,我正在寻找来自此 lofi 收音机的流媒体。

\n

更新

\n

我查看了 \xc5\x81ukasz Kwieci\xc5\x84ski 的评论,以检查官方 Discord.py Repository 上的示例。我只需要 YTDLSource 类下的“from_url”函数。然而,我现在的问题是,它会从流中播放,但会在流式传输 2-4 秒后停止播放,然后大约 1-2 分钟后,我在 stdin 中收到一条声明:“跳过前面 20 个片段,从播放列表中过期”呈黄色,播放,然后再次停止。

\n
player = await YTDLSource.from_url("https://www.youtube.com/watch?v=5qap5aO4i9A", loop=self.bot.loop, stream=True)\ninfinite_lofi.play(player, after=lambda e: print(f"Player error: {e}")) \n# ^^^ plays for a few seconds and stops, repeats every 1-2 minutes.\n
Run Code Online (Sandbox Code Playgroud)\n

Adi*_*mar 10

我的音乐机器人有代码,可以流式传输任何 YouTube 视频,无论是直播流还是普通视频,而无需下载。此代码在流式传输 2-4 秒后也不会停止音乐,这就是您遇到的问题。另一个优点是它具有完整的队列功能,这与 Groovy 和 Rythm 等机器人的功能类似。除此之外,它还有其他命令,例如removeclear,这些命令将删除队列中的指定歌曲或清除整个队列。其他命令包括np,它将显示当前正在播放的视频;queue,这将打印出整个音乐队列;vol,会显示语音客户端当前的音量;vol <integer between 1 and 100>,这将根据输入的数字以及用于使机器人加入语音频道的常规join和命令更改音量百分比。leave尝试将此代码复制粘贴到您的齿轮中,它应该可以为您工作,没有任何问题。

\n
import discord\nfrom discord.ext import commands\nimport random\nimport asyncio\nimport itertools\nimport sys\nimport traceback\nfrom async_timeout import timeout\nfrom functools import partial\nimport youtube_dl\nfrom youtube_dl import YoutubeDL\n\n# Suppress noise about console usage from errors\nyoutube_dl.utils.bug_reports_message = lambda: \'\'\n\nytdlopts = {\n    \'format\': \'bestaudio/best\',\n    \'outtmpl\': \'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s\',\n    \'restrictfilenames\': True,\n    \'noplaylist\': True,\n    \'nocheckcertificate\': True,\n    \'ignoreerrors\': False,\n    \'logtostderr\': False,\n    \'quiet\': True,\n    \'no_warnings\': True,\n    \'default_search\': \'auto\',\n    \'source_address\': \'0.0.0.0\'  # ipv6 addresses cause issues sometimes\n}\n\nffmpegopts = {\n    \'before_options\': \'-nostdin\',\n    \'options\': \'-vn\'\n}\n\nytdl = YoutubeDL(ytdlopts)\n\n\nclass VoiceConnectionError(commands.CommandError):\n    """Custom Exception class for connection errors."""\n\n\nclass InvalidVoiceChannel(VoiceConnectionError):\n    """Exception for cases of invalid Voice Channels."""\n\n\nclass YTDLSource(discord.PCMVolumeTransformer):\n\n    def __init__(self, source, *, data, requester):\n        super().__init__(source)\n        self.requester = requester\n\n        self.title = data.get(\'title\')\n        self.web_url = data.get(\'webpage_url\')\n        self.duration = data.get(\'duration\')\n\n        # YTDL info dicts (data) have other useful information you might want\n        # https://github.com/rg3/youtube-dl/blob/master/README.md\n\n    def __getitem__(self, item: str):\n        """Allows us to access attributes similar to a dict.\n        This is only useful when you are NOT downloading.\n        """\n        return self.__getattribute__(item)\n\n    @classmethod\n    async def create_source(cls, ctx, search: str, *, loop, download=False):\n        loop = loop or asyncio.get_event_loop()\n\n        to_run = partial(ytdl.extract_info, url=search, download=download)\n        data = await loop.run_in_executor(None, to_run)\n\n        if \'entries\' in data:\n            # take first item from a playlist\n            data = data[\'entries\'][0]\n\n        embed = discord.Embed(title="", description=f"Queued [{data[\'title\']}]({data[\'webpage_url\']}) [{ctx.author.mention}]", color=discord.Color.green())\n        await ctx.send(embed=embed)\n\n        if download:\n            source = ytdl.prepare_filename(data)\n        else:\n            return {\'webpage_url\': data[\'webpage_url\'], \'requester\': ctx.author, \'title\': data[\'title\']}\n\n        return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)\n\n    @classmethod\n    async def regather_stream(cls, data, *, loop):\n        """Used for preparing a stream, instead of downloading.\n        Since Youtube Streaming links expire."""\n        loop = loop or asyncio.get_event_loop()\n        requester = data[\'requester\']\n\n        to_run = partial(ytdl.extract_info, url=data[\'webpage_url\'], download=False)\n        data = await loop.run_in_executor(None, to_run)\n\n        return cls(discord.FFmpegPCMAudio(data[\'url\']), data=data, requester=requester)\n\n\nclass MusicPlayer:\n    """A class which is assigned to each guild using the bot for Music.\n    This class implements a queue and loop, which allows for different guilds to listen to different playlists\n    simultaneously.\n    When the bot disconnects from the Voice it\'s instance will be destroyed.\n    """\n\n    __slots__ = (\'bot\', \'_guild\', \'_channel\', \'_cog\', \'queue\', \'next\', \'current\', \'np\', \'volume\')\n\n    def __init__(self, ctx):\n        self.bot = ctx.bot\n        self._guild = ctx.guild\n        self._channel = ctx.channel\n        self._cog = ctx.cog\n\n        self.queue = asyncio.Queue()\n        self.next = asyncio.Event()\n\n        self.np = None  # Now playing message\n        self.volume = .5\n        self.current = None\n\n        ctx.bot.loop.create_task(self.player_loop())\n\n    async def player_loop(self):\n        """Our main player loop."""\n        await self.bot.wait_until_ready()\n\n        while not self.bot.is_closed():\n            self.next.clear()\n\n            try:\n                # Wait for the next song. If we timeout cancel the player and disconnect...\n                async with timeout(300):  # 5 minutes...\n                    source = await self.queue.get()\n            except asyncio.TimeoutError:\n                return self.destroy(self._guild)\n\n            if not isinstance(source, YTDLSource):\n                # Source was probably a stream (not downloaded)\n                # So we should regather to prevent stream expiration\n                try:\n                    source = await YTDLSource.regather_stream(source, loop=self.bot.loop)\n                except Exception as e:\n                    await self._channel.send(f\'There was an error processing your song.\\n\'\n                                             f\'```css\\n[{e}]\\n```\')\n                    continue\n\n            source.volume = self.volume\n            self.current = source\n\n            self._guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))\n            embed = discord.Embed(title="Now playing", description=f"[{source.title}]({source.web_url}) [{source.requester.mention}]", color=discord.Color.green())\n            self.np = await self._channel.send(embed=embed)\n            await self.next.wait()\n\n            # Make sure the FFmpeg process is cleaned up.\n            source.cleanup()\n            self.current = None\n\n    def destroy(self, guild):\n        """Disconnect and cleanup the player."""\n        return self.bot.loop.create_task(self._cog.cleanup(guild))\n\n\nclass Music(commands.Cog):\n    """Music related commands."""\n\n    __slots__ = (\'bot\', \'players\')\n\n    def __init__(self, bot):\n        self.bot = bot\n        self.players = {}\n\n    async def cleanup(self, guild):\n        try:\n            await guild.voice_client.disconnect()\n        except AttributeError:\n            pass\n\n        try:\n            del self.players[guild.id]\n        except KeyError:\n            pass\n\n    async def __local_check(self, ctx):\n        """A local check which applies to all commands in this cog."""\n        if not ctx.guild:\n            raise commands.NoPrivateMessage\n        return True\n\n    async def __error(self, ctx, error):\n        """A local error handler for all errors arising from commands in this cog."""\n        if isinstance(error, commands.NoPrivateMessage):\n            try:\n                return await ctx.send(\'This command can not be used in Private Messages.\')\n            except discord.HTTPException:\n                pass\n        elif isinstance(error, InvalidVoiceChannel):\n            await ctx.send(\'Error connecting to Voice Channel. \'\n                           \'Please make sure you are in a valid channel or provide me with one\')\n\n        print(\'Ignoring exception in command {}:\'.format(ctx.command), file=sys.stderr)\n        traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)\n\n    def get_player(self, ctx):\n        """Retrieve the guild player, or generate one."""\n        try:\n            player = self.players[ctx.guild.id]\n        except KeyError:\n            player = MusicPlayer(ctx)\n            self.players[ctx.guild.id] = player\n\n        return player\n\n    @commands.command(name=\'join\', aliases=[\'connect\', \'j\'], description="connects to voice")\n    async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):\n        """Connect to voice.\n        Parameters\n        ------------\n        channel: discord.VoiceChannel [Optional]\n            The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in\n            will be made.\n        This command also handles moving the bot to different channels.\n        """\n        if not channel:\n            try:\n                channel = ctx.author.voice.channel\n            except AttributeError:\n                embed = discord.Embed(title="", description="No channel to join. Please call `,join` from a voice channel.", color=discord.Color.green())\n                await ctx.send(embed=embed)\n                raise InvalidVoiceChannel(\'No channel to join. Please either specify a valid channel or join one.\')\n\n        vc = ctx.voice_client\n\n        if vc:\n            if vc.channel.id == channel.id:\n                return\n            try:\n                await vc.move_to(channel)\n            except asyncio.TimeoutError:\n                raise VoiceConnectionError(f\'Moving to channel: <{channel}> timed out.\')\n        else:\n            try:\n                await channel.connect()\n            except asyncio.TimeoutError:\n                raise VoiceConnectionError(f\'Connecting to channel: <{channel}> timed out.\')\n        if (random.randint(0, 1) == 0):\n            await ctx.message.add_reaction(\'\')\n        await ctx.send(f\'**Joined `{channel}`**\')\n\n    @commands.command(name=\'play\', aliases=[\'sing\',\'p\'], description="streams music")\n    async def play_(self, ctx, *, search: str):\n        """Request a song and add it to the queue.\n        This command attempts to join a valid voice channel if the bot is not already in one.\n        Uses YTDL to automatically search and retrieve a song.\n        Parameters\n        ------------\n        search: str [Required]\n            The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.\n        """\n        await ctx.trigger_typing()\n\n        vc = ctx.voice_client\n\n        if not vc:\n            await ctx.invoke(self.connect_)\n\n        player = self.get_player(ctx)\n\n        # If download is False, source will be a dict which will be used later to regather the stream.\n        # If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.\n        source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)\n\n        await player.queue.put(source)\n\n    @commands.command(name=\'pause\', description="pauses music")\n    async def pause_(self, ctx):\n        """Pause the currently playing song."""\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_playing():\n            embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n        elif vc.is_paused():\n            return\n\n        vc.pause()\n        await ctx.send("Paused \xe2\x8f\xb8\xef\xb8\x8f")\n\n    @commands.command(name=\'resume\', description="resumes music")\n    async def resume_(self, ctx):\n        """Resume the currently paused song."""\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n        elif not vc.is_paused():\n            return\n\n        vc.resume()\n        await ctx.send("Resuming \xe2\x8f\xaf\xef\xb8\x8f")\n\n    @commands.command(name=\'skip\', description="skips to next song in queue")\n    async def skip_(self, ctx):\n        """Skip the song."""\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        if vc.is_paused():\n            pass\n        elif not vc.is_playing():\n            return\n\n        vc.stop()\n    \n    @commands.command(name=\'remove\', aliases=[\'rm\', \'rem\'], description="removes specified song from queue")\n    async def remove_(self, ctx, pos : int=None):\n        """Removes specified song from queue"""\n\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        player = self.get_player(ctx)\n        if pos == None:\n            player.queue._queue.pop()\n        else:\n            try:\n                s = player.queue._queue[pos-1]\n                del player.queue._queue[pos-1]\n                embed = discord.Embed(title="", description=f"Removed [{s[\'title\']}]({s[\'webpage_url\']}) [{s[\'requester\'].mention}]", color=discord.Color.green())\n                await ctx.send(embed=embed)\n            except:\n                embed = discord.Embed(title="", description=f\'Could not find a track for "{pos}"\', color=discord.Color.green())\n                await ctx.send(embed=embed)\n    \n    @commands.command(name=\'clear\', aliases=[\'clr\', \'cl\', \'cr\'], description="clears entire queue")\n    async def clear_(self, ctx):\n        """Deletes entire queue of upcoming songs."""\n\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        player = self.get_player(ctx)\n        player.queue._queue.clear()\n        await ctx.send(\'**Cleared**\')\n\n    @commands.command(name=\'queue\', aliases=[\'q\', \'playlist\', \'que\'], description="shows the queue")\n    async def queue_info(self, ctx):\n        """Retrieve a basic queue of upcoming songs."""\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        player = self.get_player(ctx)\n        if player.queue.empty():\n            embed = discord.Embed(title="", description="queue is empty", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        seconds = vc.source.duration % (24 * 3600) \n        hour = seconds // 3600\n        seconds %= 3600\n        minutes = seconds // 60\n        seconds %= 60\n        if hour > 0:\n            duration = "%dh %02dm %02ds" % (hour, minutes, seconds)\n        else:\n            duration = "%02dm %02ds" % (minutes, seconds)\n\n        # Grabs the songs in the queue...\n        upcoming = list(itertools.islice(player.queue._queue, 0, int(len(player.queue._queue))))\n        fmt = \'\\n\'.join(f"`{(upcoming.index(_)) + 1}.` [{_[\'title\']}]({_[\'webpage_url\']}) | ` {duration} Requested by: {_[\'requester\']}`\\n" for _ in upcoming)\n        fmt = f"\\n__Now Playing__:\\n[{vc.source.title}]({vc.source.web_url}) | ` {duration} Requested by: {vc.source.requester}`\\n\\n__Up Next:__\\n" + fmt + f"\\n**{len(upcoming)} songs in queue**"\n        embed = discord.Embed(title=f\'Queue for {ctx.guild.name}\', description=fmt, color=discord.Color.green())\n        embed.set_footer(text=f"{ctx.author.display_name}", icon_url=ctx.author.avatar_url)\n\n        await ctx.send(embed=embed)\n\n    @commands.command(name=\'np\', aliases=[\'song\', \'current\', \'currentsong\', \'playing\'], description="shows the current playing song")\n    async def now_playing_(self, ctx):\n        """Display information about the currently playing song."""\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        player = self.get_player(ctx)\n        if not player.current:\n            embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n        \n        seconds = vc.source.duration % (24 * 3600) \n        hour = seconds // 3600\n        seconds %= 3600\n        minutes = seconds // 60\n        seconds %= 60\n        if hour > 0:\n            duration = "%dh %02dm %02ds" % (hour, minutes, seconds)\n        else:\n            duration = "%02dm %02ds" % (minutes, seconds)\n\n        embed = discord.Embed(title="", description=f"[{vc.source.title}]({vc.source.web_url}) [{vc.source.requester.mention}] | `{duration}`", color=discord.Color.green())\n        embed.set_author(icon_url=self.bot.user.avatar_url, name=f"Now Playing ")\n        await ctx.send(embed=embed)\n\n    @commands.command(name=\'volume\', aliases=[\'vol\', \'v\'], description="changes Kermit\'s volume")\n    async def change_volume(self, ctx, *, vol: float=None):\n        """Change the player volume.\n        Parameters\n        ------------\n        volume: float or int [Required]\n            The volume to set the player to in percentage. This must be between 1 and 100.\n        """\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I am not currently connected to voice", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n        \n        if not vol:\n            embed = discord.Embed(title="", description=f" **{(vc.source.volume)*100}%**", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        if not 0 < vol < 101:\n            embed = discord.Embed(title="", description="Please enter a value between 1 and 100", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        player = self.get_player(ctx)\n\n        if vc.source:\n            vc.source.volume = vol / 100\n\n        player.volume = vol / 100\n        embed = discord.Embed(title="", description=f\'**`{ctx.author}`** set the volume to **{vol}%**\', color=discord.Color.green())\n        await ctx.send(embed=embed)\n\n    @commands.command(name=\'leave\', aliases=["stop", "dc", "disconnect", "bye"], description="stops music and disconnects from voice")\n    async def leave_(self, ctx):\n        """Stop the currently playing song and destroy the player.\n        !Warning!\n            This will destroy the player assigned to your guild, also deleting any queued songs and settings.\n        """\n        vc = ctx.voice_client\n\n        if not vc or not vc.is_connected():\n            embed = discord.Embed(title="", description="I\'m not connected to a voice channel", color=discord.Color.green())\n            return await ctx.send(embed=embed)\n\n        if (random.randint(0, 1) == 0):\n            await ctx.message.add_reaction(\'\')\n        await ctx.send(\'**Successfully disconnected**\')\n\n        await self.cleanup(ctx.guild)\n\n\ndef setup(bot):\n    bot.add_cog(Music(bot))\n
Run Code Online (Sandbox Code Playgroud)\n