In this article, we will see how we can play youtube video in python. In order to play youtube videos in python we need pafy and vlc module.
Pafy is a Python library to download YouTube content and retrieve metadata. Below is the command to install pafy
Python3 1==
Output :
Another example
Python3 1==
pip install pafyVLC : is a python library to use the functionality of the vlc media player. In order to use the vlc module in python the user system should have a compatible version of VLC player as well. Below is the command to install vlc module
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 videoBelow is the implementation
# importing vlc module
import vlc
# importing pafy module
import pafy
# url of the video
url = "https://www.youtube.com/ = 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()
Another example
# importing vlc module
import vlc
# importing pafy module
import pafy
# url of the video
url = "https://www.youtube.com/=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()
Output :

