首页 > 解决方案 > Discord bot 无法播放 youtube 视频超过 ~60 秒

问题描述

几周前,我开始了一个不和谐机器人作为一个有趣的副项目。从昨天开始,我一直在尝试让我的机器人搜索 youtube 视频并在语音频道中播放它们(主要是歌曲)。

机器人使用查询正确搜索 youtube 并找到 youtube 视频,开始播放它,但由于某种原因,大约 60 秒后(无论视频如何,总是在同一时间),机器人突然不再提供音频,然后卡在某个地方(不是一条错误消息,但机器人只是停止响应)。

以下是代码片段:

# first two words are activation keywords for the bot, then its the youtube query
query = ' '.join(message.message.content.split()[2:])
youtube = build("youtube", "v3", developerKey=yt_token)
search_response = youtube.search().list(q=query, part="id,snippet", maxResults=5).execute()
video_id = search_response['items'][0]['id']['videoId']
video_url = "https://www.youtube.com/watch?v=" + video_id

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
     ydl.download([video_url])
await play_audio(message, 'song.mp3')

(播放后我删除了歌曲.mp3)

我的 ydl 选项是

ydl_opts = {
    "postprocessors":[{
        "key": "FFmpegExtractAudio", # download audio only
        "preferredcodec": "mp3", # other acceptable types "wav" etc.
        "preferredquality": "192" # 192kbps audio
    }],
    "format": "bestaudio/best",
    "outtmpl": "song.mp3"
}

而且我的 play_audio 功能是

async def play_audio(message, audio_name):
        channel = message.message.author.voice.channel
        vc = await channel.connect()
        time.sleep(0.5)
        vc.play(discord.FFmpegPCMAudio(audio_name))
        while vc.is_playing():
            time.sleep(1)
        vc.stop()
        await vc.disconnect()

我知道 time.sleep() 调用被阻塞,但我现在并不真正核心。

有人遇到过这个问题吗?对于短视频(少于 60 秒),一切正常。也许是一个 ffmpeg 选项?

标签: pythonffmpegyoutubediscordbots

解决方案


推荐阅读