如何从 Python 中的 Youtube URL 流式传输音频(无需下载)? [英] How to stream audio from a Youtube URL in Python (without download)?

查看:17
本文介绍了如何从 Python 中的 Youtube URL 流式传输音频(无需下载)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一种直接从 python 代码流式传输 youtube url(最好是仅音频,尽管这并不重要)的方法.我尝试了很多东西,但似乎没有一个真正有效.到目前为止,我能够使用 youtube 数据 api 搜索视频或播放列表,抓取第一个视频或播放列表并将其传递给 pafy 以获得不同的流媒体 URL.有谁知道一种无需先下载视频即可通过 python 播放 youtube 音频/视频的方法?我认为可以使用诸如 mplayer 或 vlc 之类的 cmd 行工具使用子进程为 cmd 行弹出一个 cmd 并传入 url,但我被卡住了.需要任何帮助.请!这是我的以下代码:

导入 argparse进口帕菲从 googleapiclient.discovery 导入构建从 googleapiclient.errors 导入 HttpErrorDEVELOPER_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)播放列表 = pafy.get_playlist(url)def youtube_search(选项):youtube = 构建(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)search_response = youtube.search().list(q='你好世界',部分='id,片段',maxResults=options.max_results).执行()视频 = []播放列表 = []频道 = []对于 search_response.get('items', []) 中的 search_result:如果 search_result['id']['kind'] == 'youtube#video':视频.append('%s' % (search_result['id']['videoId']))elif search_result['id']['kind'] == 'youtube#channel':channel.append('%s' % (search_result['id']['channelId']))elif search_result['id']['kind'] == 'youtube#playlist':playlists.append('%s' % (search_result['id']['playlistId']))如果视频:打印('视频:{0}'.format(视频))pafy_video(视频[0])elif 播放列表:打印('播放列表:{0}'.format(播放列表))pafy_video(播放列表[0])#https://www.youtube.com/watch?v=rOU4YiuaxAM#url = 'https://www.youtube.com/watch?v={0}'.format(videos[0])#打印(网址)如果 __name__ == '__main__':解析器 = argparse.ArgumentParser()parser.add_argument('--q', help='搜索词', default='Google')parser.add_argument('--max-results', help='Max results', default=3)args = parser.parse_args()youtube_search(参数)

Tldr;我想直接从 python 代码流式传输 youtube 视频(使用 url 或 id),而无需先下载视频

谢谢!

解决方案

pafy 根据其 文档 不直接列出播放媒体(至少我没有找到).

但是我们可以用它来获取正确的url,然后使用vlc等播放器直接播放,无需下载.

您可以从这里下载vlc

首先,我们使用 pafy

youtube 获取正确/最佳 URL

导入pafy进口vlcurl = "https://www.youtube.com/watch?v=bMt47wvK6u0";视频 = pafy.new(url)最佳 = video.getbest()playurl = best.url

这里 playurl 是播放的最佳 URL.然后我们用VLC来播放.

Instance = vlc.Instance()播放器 = Instance.media_player_new()媒体 = Instance.media_new(playurl)Media.get_mrl()player.set_media(媒体)播放器播放()

这将打开一个没有控件(播放/暂停/停止等)的窗口.您可以在 repr 窗口或 python 提示符下运行这些命令(取决于您的使用方式)
您将需要使用 vlc 命令相应地构建一个,例如

<预><代码>>>>player.pause() #-- 暂停视频>>>player.play() #-- 恢复暂停的视频.在旧版本上,# 这个函数叫做resume>>>player.stop() #-- 停止/结束视频

I have been trying to create a way to stream a youtube url (preferably audio only, although this doesn't matter too much) right from python code. I have tried numerous things but none really seem to work. So far, I am able to search for videos or playlists using youtube data api, grab the first video or playlist and pass it into pafy to get different streaming urls. Does anyone know of a way to play youtube audio/video through python without downloading the video first? I would think it is possible with a cmd line tool such as mplayer or vlc using the sub process to pop open a cmd for the cmd line and pass in the url, but I am stuck. Any help is needed. Please! Here is my following code:

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; I would like to stream a youtube video (using the url or id) straight from python code without downloading the video first

Thank you!

解决方案

pafy according to its documentation do not list playing media directly (at least I didn't find any).

However we can use it to get correct url, and then use player such as vlc to play directly without downloading.

You can download vlc from here

First we get correct / best URL from youtube using pafy

import pafy
import vlc

url = "https://www.youtube.com/watch?v=bMt47wvK6u0"
video = pafy.new(url)
best = video.getbest()
playurl = best.url

Over here playurl is best URL to play. Then we use VLC to play it.

Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()

This will open a window with no controls (play/pause/stop etc). You can run these command on the repr window or at python prompt (depending upon how you are using it)
You will need to build one accordingly using vlc commands such as

>>> player.pause() #-- to pause video
>>> player.play()  #-- resume paused video. On older versions, 
                   #     this function was called resume
>>> player.stop()  #-- to stop/end video

这篇关于如何从 Python 中的 Youtube URL 流式传输音频(无需下载)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆