我一直在尝试创建一种方法来直接从 python 代码流式传输 youtube url(最好是音频,尽管这无关紧要)。我尝试了很多东西,但似乎都没有用。到目前为止,我能够使用 youtube 数据 api 搜索视频或播放列表,获取第一个视频或播放列表并将其传递到 pafy 以获取不同的流媒体 url。有谁知道无需先下载视频即可通过 python 播放 youtube 音频/视频的方法?我认为可以使用 mplayer 或 vlc 等 cmd 行工具使用子进程弹出打开 cmd 行的 cmd 并传入 url,但我被卡住了。需要任何帮助。请!这是我的以下代码:
import argparse
import pafy
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
DEVELOPER_KEY = 'DEVELOPER KEY'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def pafy_video(video_id):
url = 'https://www.youtube.com/watch?v={0}'.format(video_id)
vid = pafy.new(url)
def pafy_playlist(playlist_id)
url = "https://www.youtube.com/playlist?list={0}".format(playlist_id)
playlist = pafy.get_playlist(url)
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q='Hello world',
part='id,snippet',
maxResults=options.max_results
).execute()
videos = []
playlists = []
channels = []
for search_result in search_response.get('items', []):
if search_result['id']['kind'] == 'youtube#video':
videos.append('%s' % (search_result['id']['videoId']))
elif search_result['id']['kind'] == 'youtube#channel':
channels.append('%s' % (search_result['id']['channelId']))
elif search_result['id']['kind'] == 'youtube#playlist':
playlists.append('%s' % (search_result['id']['playlistId']))
if videos:
print('Videos:{0}'.format(videos))
pafy_video(videos[0])
elif playlists:
print('Playlists:{0}'.format(playlists))
pafy_video(playlists[0])
#https://www.youtube.com/watch?v=rOU4YiuaxAM
#url = 'https://www.youtube.com/watch?v={0}'.format(videos[0])
#print(url)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--q', help='Search term', default='Google')
parser.add_argument('--max-results', help='Max results', default=3)
args = parser.parse_args()
youtube_search(args)
Tldr;我想直接从 python 代码流式传输 youtube 视频(使用 url 或 id)而不先下载视频
谢谢!
原文由 Nick D 发布,翻译遵循 CC BY-SA 4.0 许可协议
pafy
根据其 文档,不要直接列出播放媒体(至少我没有找到)。但是我们可以用它获取正确的url,然后使用播放器如
vlc
直接播放,无需下载。你可以 从这里下载vlc
首先,我们从
youtube
使用pafy
在这里
playurl
是最好玩的网址。然后我们用VLC来播放。这将打开一个没有控件(播放/暂停/停止等)的窗口。您可以在
repr
窗口或 python 提示符下运行这些命令(取决于您的使用方式)您将需要使用 vlc 命令相应地构建一个,例如