Member-only story
Playing a YouTube Video using Python
1 min readNov 30, 2024
This Python script uses the pywhatkit
library to search for a song on YouTube and play it. Here's a detailed explanation of the code:
Step-by-Step Explanation:
Importing the pywhatkit
library:
import pywhatkit
- The
pywhatkit
library is a Python module that allows various tasks, including sending WhatsApp messages, searching on Google, and playing videos on YouTube.
Getting the song name from the user:
Song = input("Enter Song Name: ")
- The program prompts the user to enter the name of the song they want to play.
Playing the song on YouTube:
pywhatkit.playonyt(Song)
- The
playonyt
method inpywhatkit
searches for the entered song on YouTube and plays the first result in the user's default web browser.
Handling success and errors:
print("Successfully Played!")
- If the song is successfully found and played, a success message is displayed.
except: print("An Unexpected Error!")
- If any error occurs (e.g., the song name isn’t found or there’s an internet issue), an error message is displayed instead.
Example Run:
- Input:
Enter Song Name: Shape of You
Output:
- The web browser opens and plays the “Shape of You” song on YouTube.
- If successful, the program prints:
Successfully Played!