Tooling Tuesday - Playing YouTube videos in Python
YouTube, a place where we can learn a new skill, watch people play games, and watch endless cat videos... But what if you wanted to play a YouTube video outside the web browser? Say in a media player, triggered by a sensor, key press etc? Well dear reader we can.
So what is it?
Pafy is a Python library that can play content from YouTube in your chosen media player. Created by np1 this library is super simple to install and use.
So how do I install it?
On Linux machines via the terminal and using pip.
sudo pip install pafy
On Windows
pip.exe install pafy
How to use it
Using your favourite Python editor (I'm using Mu because it is easy to use and explain how to use in sessions)
To use pafy
we first need to import the library, and then tell it the URL of the YouTube video. In this case an LGR video where he unboxes lots of retro computer stuff.
import pafy
url = "https://www.youtube.com/watch?v=1yNfzVABvCM"
Now lets tell pafy about the URL.
video = pafy.new(url)
Pafy features
Pafy can also be used to get the details of a video, so lets get the title of the video that we have chosen.
video.title
This will return
LGR - Opening Stuff You Sent Me! October 2018
Or we can see the rating, and see a description of the chosen video by using...
video.rating
print(video.description)
Another cool feature is that we can also check out the best video formats for the media.
best = video.getbest()
And to find out the best URL that we can use to stream with VLC...
best.url
And to play that URL with the Python 3 VLC library...
In last week's post we covered how to use VLC with Python, find out more by taking a quick look.
import vlc, pafy
url = "https://www.youtube.com/watch?v=1yNfzVABvCM"
video = pafy.new(url)
best = video.getbest()
media = vlc.MediaPlayer(best.url)
media.play()
Ok so can I build something quick with it?
Yup, lets make a quick app that will ask for a YouTube URL and then open it in VLC. For this we need to have VLC and VLC Python library installed.
As usual we import the libraries at the start.
import vlc, pafy
Then we create a variable called "url" and in there we store the users URL using the input function.
url = input("Paste your YouTube URL here :>> ")
Then we tell pafy about the video.
video = pafy.new(url)
Get the best video stream.
best = video.getbest()
media = vlc.MediaPlayer(best.url)
Play the media.
media.play()
Run the code and it will ask for the YouTube URL, and for my test I chose a BigClive video.
Wondering why the video is a little stuttery? That is because I am recording the desktop while playing a video on my Teclast F7, which only has a Celeron CPU
If you want to stop the video, in the REPL (Python shell)
media.stop()