python - 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 选项?
解决方案
推荐阅读
- php - Fopen如何在php中读取png文件
- python - 如何使用 Pandas 处理 Paramiko 从内存中的远程 shell 命令返回的数据?
- jquery - 如何在asp.net核心中使用ajax将具有不同名称的元素列表传递给控制器?
- mysql - 检查条件时出现 SQL CASE 语句错误
- amazon-dynamodb - 在 Dynamodb 中获取聚合计数
- php - 通过“X-Powered-By”缺少反 CSRF 令牌和服务器泄漏信息:如何设置?
- google-cloud-platform - Terraform:“创建防火墙时出错:googleapi:错误 403:需要‘compute.firewalls.create’”
- java - 在 Java 方法中声明的任何内容都是本地的(某些特殊情况除外),对吗?
- windows - 在 Windows Powershell 中创建别名
- css - React NavLink:添加到内部标签的边距不可点击