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
Related Articles
Continue your learning journey with these related topics
Databases
2 min readHow to Read a Folder of CSVs in Python Using DuckDB
Explore the power of DuckDB, an efficient open-source analytical database system for processing large datasets. This post delves into reading a folder of CSVs using DuckDB in Python, demonstrating its advantages over traditional methods like Pandas.
5/30/2023Read More
Fundamentals
1 min read7 ways to create a Pandas DataFrame in Python
Learn various ways to create a Pandas DataFrame, including from a dictionary of arrays, list of dictionaries, 2D Numpy array, CSV file, SQL query, Excel file and also specifying index while creating it.
2/14/2023Read More
Fundamentals
1 min read6 ways to efficiently store data in Python
Learn various ways to store data efficiently in Python, including relational databases, NoSQL databases, data serialization, data compression, and data containers like NumPy array and Pandas DataFrame.
2/13/2023Read More
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