r/madeinpython • • Nov 12 '21

Download mp3 from youtube

This is a little script I worked out from a few things I saw online.

You can use it to get individual videos but the real joy is playlists XD

Make sure you install the libraries to use it

Enjoy!

from pytube import YouTube, Playlist
import os
import random

def getPlaylist(playlist_link):
    video_links = Playlist(playlist_link).video_urls
    video_titles = []
    for link in video_links:
        video_titles.append(YouTube(link).title)
    print(len(video_titles))
    print(len(video_links))
    for i in range(len(video_links)):
        yt = YouTube(video_links[i])
        yt.title=video_titles[i]
        print(yt.title)
        video = yt.streams.filter(only_audio=True).first()
        out_file = video.download(output_path=".")
        base, ext = os.path.splitext(out_file)
        new_file = base + '.mp3'
        os.rename(out_file, new_file)
        print('done')

def getLink(link):
    print(link)
    yt = YouTube(link)
    print(yt.title)
    video = yt.streams.filter(only_audio=True).first()
    out_file = video.download(output_path=".")
    base, ext = os.path.splitext(out_file)
    new_file = base + '.mp3'
    os.rename(out_file, new_file)
    print('done')

playlist_link = ''  #link goes here
link=''     #link goes here
# Uncomment what you want to use
#getPlaylist(playlist_link)      #for playlists
#getLink(link)                  #for single videos
18 Upvotes

2 comments sorted by

1

u/wickeddawg Nov 12 '21

thanks for sharing

1

u/[deleted] Nov 12 '21

Sure thing :)