使用Python播放 Youtube 视频
在本文中,我们将了解如何在Python中播放 youtube 视频。为了在Python中播放 youtube 视频,我们需要pafy和vlc模块。
Pafy是一个Python库,用于下载 YouTube 内容和检索元数据。下面是安装pafy的命令
pip install pafy
VLC :是一个使用 vlc 媒体播放器功能的Python库。为了在Python中使用 vlc 模块,用户系统也应该有一个兼容版本的 VLC 播放器。下面是安装 vlc 模块的命令
pip install python-vlc
Steps for implementation :
1. Import the pafy and vlc module
2. Create a variable having URL of the video
3. Create a pafy object using the link
4. Get the best quality stream of the given youtube link
5. Create a vlc MediaPlayer object by passing the best Stream
6. Play the video
下面是实现
# importing vlc module
import vlc
# importing pafy module
import pafy
# url of the video
url = "https://www.youtube.com/watch?v = vG2PNdI8axo"
# creating pafy object of the video
video = pafy.new(url)
# getting best stream
best = video.getbest()
# creating vlc media player object
media = vlc.MediaPlayer(best.url)
# start playing video
media.play()
输出 :
另一个例子
# importing vlc module
import vlc
# importing pafy module
import pafy
# url of the video
url = "https://www.youtube.com/watch?v=il_t1WVLNxk&list=PLqM7alHXFySGqCvcwfqqMrteqWukz9ZoE"
# creating pafy object of the video
video = pafy.new(url)
# getting stream at index 0
best = video.streams[0]
# creating vlc media player object
media = vlc.MediaPlayer(best.url)
# start playing video
media.play()
输出 :