create_ytdl_player 是创建播放器的旧方法。使用discord.py@rewrite (> v.1.0),播放音乐有点复杂。有两种播放音乐的方法。对于这两种方式,都需要使用 FFmpeg,所以你必须install it。
这里有两种播放视频的方法(youtube-dl 和 ffmpeg):
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from youtube_dl import YoutubeDL
@bot.command(brief="Plays a single video, from a youtube URL") #or bot.command()
async def play(ctx, url):
voice = get(client.voice_clients, guild=ctx.guild)
YDL_OPTIONS = {
'format': 'bestaudio',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': 'song.%(ext)s',
}
with YoutubeDL(Music.YDL_OPTIONS) as ydl:
ydl.download("URL", download=True)
if not voice.is_playing():
voice.play(FFmpegPCMAudio("song.mp3"))
voice.is_playing()
await ctx.send(f"Now playing {url}")
else:
await ctx.send("Already playing song")
return
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
from youtube_dl import YoutubeDL
@bot.command(brief="Plays a single video, from a youtube URL")
async def play(ctx, url):
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(client.voice_clients, guild=ctx.guild)
if not voice.is_playing():
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(video_link, download=False)
URL = info['formats'][0]['url']
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
voice.is_playing()
else:
await ctx.send("Already playing song")
return
这些命令只会播放歌曲,因此您必须对所有其他命令(加入、离开等)进行编程。
网上有很多例子,习惯了制作音乐机器人后应该看看。
参考: VoiceClient 文档。