gpt4 book ai didi

python - 如何使用 youtube_dl 和 FFMpegPCM 音频播放来自 youtube 的直播流? Discord.py 重写

转载 作者:行者123 更新时间:2023-12-04 23:06:52 26 4
gpt4 key购买 nike

我一直在为不和谐开发一个简单的音乐机器人,我的 friend 们要求提供一个功能,您可以在其中流式传输来自 youtube 直播的音频。这让我很困惑,我找不到任何好的资源来解决这个问题。这是重要的代码:

from discord.ext import commands
from discord.ext import tasks
import discord
from itertools import cycle
import os
from dotenv import load_dotenv
import asyncio
from ytsearch import searchr
from discord.utils import get
from discord import FFmpegPCMAudio
from youtube_dl import YoutubeDL

list_to_play = []
paused = False

load_dotenv()
TOKEN = os.getenv("TOKEN")

bot = commands.Bot(command_prefix='-')
@bot.event
async def on_ready():
for guild in bot.guilds:
print(
f'{bot.user} is connected to the following guild(s):\n'
f'{guild.name}(id: {guild.id})'
)
change_status.start()
play_the_list.start()

status = cycle(['Music is here!','More features soon!'])

@tasks.loop(seconds=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(status)))

async def playa(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(bot.voice_clients, guild=ctx.guild)
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
URL = info['url']
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
voice.is_playing()


@tasks.loop(seconds=3)
async def play_the_list():
global list_to_play

if paused == False:

if len(list_to_play) != 0:
ctx = list_to_play[0][1]

voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing() == False:

if len(list_to_play) != 0:
await playa(list_to_play[0][1],list_to_play[0][0])
del list_to_play[0]




bot.run(TOKEN)
我正在寻找类似 playa() 的东西(或编辑 playa() 以便播放实时视频的方法)

最佳答案

我建议查看此类播放器的官方示例:

  • https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py

  • 这些片段可能会有所帮助:)
    对于 FFmpeg 类:
    data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

    filename = data['url'] if stream else ytdl.prepare_filename(data)
    命令:
    @commands.command()
    async def stream(self, ctx, *, url):
    """Streams from a url (same as yt, but doesn't predownload)"""
    async with ctx.typing():
    player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
    ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)

    await ctx.send(f'Now playing: {player.title}')

    关于python - 如何使用 youtube_dl 和 FFMpegPCM 音频播放来自 youtube 的直播流? Discord.py 重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70281576/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com