How to download a youtube video in mp3 using Python
• 0 minCarefull, 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.