【问题标题】:potato quality audio coming from bot来自机器人的土豆质量音频
【发布时间】:2020-07-24 00:17:14
【问题描述】:

当我通过我的机器人播放音频时,它听起来很糟糕,我有一个快速的互联网连接,那么这可能是什么原因造成的?我在 Raspberry Pi 3 上运行我的机器人。我使用 FFMpeg。 RPI 是否会以某种方式成为瓶颈。是我的代码吗?

我的代码的简化版本:

@client.command()
async def play(ctx):
    channel = client.get_channel(ctx.message.author.voice.channel.id)
    voice = await channel.connect()
    if not voice.is_playing():
        voice.play(await discord.FFMpegOpusAudio(source='/path/to/file'))
        while voice.is_playing():
            await asyncio.sleep(1)
    discord.AudioSource.cleanup(str(ctx.message.author.voice.channel.id))

【问题讨论】:

  • 你在哪里下载视频?
  • 我使用名为 pafy 的库从 youtube 下载视频。

标签: python-3.x ffmpeg discord.py


【解决方案1】:

查看pafy 文档,您必须这样做:

def download_song(url)
    video = pafy.new(url)
    best = video.getbest()
    best.download(quiet=False)

不过,我建议使用:

  • youtube-dl:

    pip install youtube-dl
    
    from youtube_dl import YoutubeDL
    
    ydl_opts = {
        'format': 'bestaudio/best',
        'noplaylist':'True',
        'outtmpl': 'song.%(ext)s'
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    
    def download_song(arg, url=True):
        with YoutubeDL(ydl_opts) as ydl:
            query = f"ytsearch:{arg}" if url else arg
            data = ydl.extract_info(query, download=True)
        return data if url else data['entries'][0]
    
    def display_info(data):
        video_info = {
            'title': data['title']
            'duration': data['duration']
            'uploader': data['uploader']
            'thumbnail': data['thumbnail']
            'url': data['webpage_url']
            'channel': data['channel_url']
        }
        for key, val in video_info.items():
            print(f"{key}: {val}")
    

    此功能将允许您从 URL 和查询(例如“30 秒视频”)下载歌曲。 youtube_dl 提供a lot of options

  • Wavelink(discord.py 的 lavalink 包装器 → 更好的音频和音频控制):

    pip install lavalink
    
    #Wavelink github example
    import discord
    import wavelink
    from discord.ext import commands
    
    
    class Bot(commands.Bot):
    
        def __init__(self):
            super(Bot, self).__init__(command_prefix=['audio ', 'wave ','aw '])
    
            self.add_cog(Music(self))
    
        async def on_ready(self):
            print(f'Logged in as {self.user.name} | {self.user.id}')
    
    
    class Music(commands.Cog):
    
        def __init__(self, bot):
            self.bot = bot
    
            if not hasattr(bot, 'wavelink'):
                self.bot.wavelink = wavelink.Client(bot=self.bot)
    
            self.bot.loop.create_task(self.start_nodes())
    
        async def start_nodes(self):
            await self.bot.wait_until_ready()
    
            # Initiate our nodes. For this example we will use one server.
            # Region should be a discord.py guild.region e.g sydney or us_central (Though this is not technically required)
            await self.bot.wavelink.initiate_node(host='127.0.0.1',
                                                  port=2333,
                                                  rest_uri='http://127.0.0.1:2333',
                                                  password='youshallnotpass',
                                                  identifier='TEST',
                                                  region='us_central')
    
        @commands.command(name='connect')
        async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
            if not channel:
                try:
                    channel = ctx.author.voice.channel
                except AttributeError:
                    raise discord.DiscordException('No channel to join. Please either specify a valid channel or join one.')
    
            player = self.bot.wavelink.get_player(ctx.guild.id)
            await ctx.send(f'Connecting to **`{channel.name}`**')
            await player.connect(channel.id)
    
        @commands.command()
        async def play(self, ctx, *, query: str):
            tracks = await self.bot.wavelink.get_tracks(f'ytsearch:{query}')
    
            if not tracks:
                return await ctx.send('Could not find any songs with that query.')
    
            player = self.bot.wavelink.get_player(ctx.guild.id)
            if not player.is_connected:
                await ctx.invoke(self.connect_)
    
            await ctx.send(f'Added {str(tracks[0])} to the queue.')
            await player.play(tracks[0])
    
    
    bot = Bot()
    bot.run('TOKEN')
    

    这个比较复杂,但可以让您更好地控制音乐播放器。就个人而言,我认为youtube-dl 足以播放不和谐的音频,但这取决于你。

【讨论】:

  • 好,我先试试ytdl,看看能不能满足我。
  • 好的,所以 ytdl 下载歌曲但查看代码,而不是以 mp3 格式下载,而是以 webm 格式下载。对不起,如果我错了,我之前没有使用过这个库,所以我不知道它是如何工作的。它也剪掉了一大堆。
  • 现在应该输出为 mp3。我没有下载就播放音频,所以我从未尝试下载视频^^
  • 哦,你能做到吗?
  • 我写了一个关于playing audio with youtube-dl and ffmpeg的相当完整的答案,里面有两种方法。
猜你喜欢
  • 2018-12-22
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 2021-05-27
  • 1970-01-01
  • 2021-11-29
相关资源
最近更新 更多