How to download a youtube video in mp3 using Python
7-Day Challenge
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet
Carefull, this might not be legal depending on where you do it.
In order to do this, you will have to install the youtube_dl library.
Installation
pip3 install youtube-dl
The code
import youtube_dl
import os
def get_song(filename, url):
"""Provided and url and a filename download the song."""
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, f"./{filename}.mp3")
if __name__ == "__main__":
# We download the video's mp3 and save it under "song.mp3"
get_song("song","https://www.youtube.com/watch?v=U-xsosv6uM0")
Here you are! Now you know how to download a youtube video in mp3 using Python.
7-Day Challenge
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet
Free Newsletter
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚
Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee