discord.py如何在不和谐的语音通道中播放特定的mp3(或特定的youtube视频)?

时间:2020-02-27 06:33:36

标签: discord discord.py

现在就算了,我还是一个初学者,所以我不确定如何解决这个问题,而且许多教程都是预先重写的。任何帮助深表感谢!

2 个答案:

答案 0 :(得分:1)

要播放mp3文件,必须确保从链接here下载 FFMPEG 。安装并解压缩后,将其添加到您的路径

添加到路径的说明 控制面板->系统->高级->环境变量->系统变量->路径->然后将bin文件添加到刚刚下载的文件中。

安装完成后,必须在代码中创建一个VoiceClient对象。有多种方法可以做到这一点。一种(我已经使用过的)是使用功能channel.connect()来加入频道并返回VoiceClient对象。一旦有了加入客户端对象,就可以使用函数VoiceClient.play()。参数(找到here)接受音频源。这就是FFMPEG出现的地方。在参数-> VoiceClient.play(discord.FFmpegPCMAudio("myAudioFile.mp3"))中。

如果此行在查找FFMPEG时遇到问题,则可以像这样插入可执行文件的路径-> VoiceClient.play(discord.FFmpegPCMAudio( executable = "C:/ffmpeg/bin/ffmpeg.exe" , source = "myAudioFile.mp3"))请注意,executable字符串和source字符串因您的FFMPEG位置而异以及您的mp3文件位置

这就是在on_voice_state_update函数中使用的示例代码的样子:

@bot.event async def on_voice_state_update(member,before,after): VC = await after.channel.connect() VC.play(discord.FFmpegPCMAudio("MyAudioFile.mp3"))

答案 1 :(得分:0)

请确保为此安装PyNaCl并导入naclos

mp3示例:

@bot.command()
async def play(ctx):
    if ctx.author.voice.channel:
        if not ctx.guild.voice_client: # error would be thrown if bot already connected, this stops the error
            player = await ctx.author.voice.channel.connect()
        else:
            player = ctx.guild.voice_client
        player.play(discord.FFmpegPCMAudio("your.mp3")) # or "path/to/your.mp3"
    else:
        await ctx.send("Please connect to a voice channel.")

ytdl示例:

@bot.command()
async def play(ctx, url=None):
    if ctx.author.voice.channel:
        if not ctx.guild.voice_client:
            player = await ctx.author.voice.channel.connect()
        else:
            player = ctx.guild.voice_client
        options = {
            "postprocessors":[{
                "key": "FFmpegExtractAudio", # download audio only
                "preferredcodec": "mp3", # other acceptable types "wav" etc.
                "preferredquality": "192" # 192kbps audio
            }],
            "format": "bestaudio/best",
            "outtmpl": "yt_song.mp3" # downloaded file name
        }
        with youtube_dl.YoutubeDL(options) as dl:
            dl.download([url])
        player.play(discord.FFmpegPCMAudio("yt_song.mp3"))
        playing = player.is_playing()
        while playing: # not compulsory
            await asyncio.sleep(1)
            playing = player.is_playing()
        os.remove("yt_song.mp3") # delete the file after use
    else:
        await ctx.send("Please connect to a voice channel.")

参考: