create_ytdl_player
是创建玩家的旧方法。和不和谐.py@rewrite https://discordpy.readthedocs.io/en/latest/(> v.1.0),播放音乐有点复杂。有两种播放音乐的方式。对于这两种方式,都需要使用 FFmpeg,因此您必须安装它 https://www.youtube.com/watch?v=a_KqycyErd8.
这里有两种播放视频的方法(youtube-dl
and 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
- 无需下载音乐。这种方式播放音乐更简单,但是,这会导致一个已知问题,这里解释得很好 https://support.discord.com/hc/en-us/articles/360035010351--Known-Issue-Music-Bots-Not-Playing-Music-From-Certain-Sources所以你必须添加一个
FFMPEG_OPTIONS
多变的:
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 https://discordpy.readthedocs.io/en/latest/api.html?highlight=voice#discord.VoiceClient文档。