Discord.py|播放url中的音频 [英] discord.py | play audio from url
本文介绍了Discord.py|播放url中的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让我的机器人从URL播放音频,但我不想下载文件...
以下是我的代码:
@commands.command(name='test')
async def test(self, ctx):
search = "morpheus tutorials discord bot python"
if ctx.message.author.voice == None:
await ctx.send(embed=Embeds.txt("No Voice Channel", "You need to be in a voice channel to use this command!", ctx.author))
return
channel = ctx.message.author.voice.channel
voice = discord.utils.get(ctx.guild.voice_channels, name=channel.name)
voice_client = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
if voice_client == None:
await voice.connect()
else:
await voice_client.move_to(channel)
search = search.replace(" ", "+")
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
video_ids = re.findall(r"watch?v=(S{11})", html.read().decode())
#################################
await ctx.send("https://www.youtube.com/watch?v=" + video_ids[0])
# AND HERE SHOULD IT PLAY
#################################
我尝试了create_ytdl_player方法,但发现它不再受支持,我该怎么办?
推荐答案
使用pafy。
首先导入一些内容并设置FFmpeg选项...
import pafy
from discord import FFmpegPCMAudio, PCMVolumeTransformer
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn'}
然后播放
@commands.command(name='test')
async def test(self, ctx):
search = "morpheus tutorials discord bot python"
if ctx.message.author.voice == None:
await ctx.send(embed=Embeds.txt("No Voice Channel", "You need to be in a voice channel to use this command!", ctx.author))
return
channel = ctx.message.author.voice.channel
voice = discord.utils.get(ctx.guild.voice_channels, name=channel.name)
voice_client = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
if voice_client == None:
voice_client = await voice.connect()
else:
await voice_client.move_to(channel)
search = search.replace(" ", "+")
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
video_ids = re.findall(r"watch?v=(S{11})", html.read().decode())
await ctx.send("https://www.youtube.com/watch?v=" + video_ids[0])
song = pafy.new(video_ids[0]) # creates a new pafy object
audio = song.getbestaudio() # gets an audio source
source = FFmpegPCMAudio(audio.url, **FFMPEG_OPTIONS) # converts the youtube audio source into a source discord can use
voice_client.play(source) # play the source
这篇关于Discord.py|播放url中的音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文