Download YouTube Videos using Python

pytube is a lightweight, Pythonic, dependency-free, library (and command-line utility) for downloading YouTube Videos.

Download YouTube Video using pytube and Convert the audio file to MP3 format using MoviePy


import os
from pytube import YouTube
from moviepy.editor import AudioFileClip

def download_yt_as_mp3(folder, yid, filename):
    video_url = "https://www.youtube.com/watch?v=" + yid
    mp3_filepath = "H:/Jukebox/" + folder + "/" + filename + ".mp3"

    # Create a YouTube object
    yt = YouTube(video_url)

    # Get the audio stream
    stream = yt.streams.filter(only_audio=True).first()

    # Download the audio file
    out_file = stream.download(output_path='.')

    # Convert the audio file to MP3 format using MoviePy
    AudioFileClip(out_file).write_audiofile(mp3_filepath)

    # Delete the original audio file
    os.remove(out_file)

    print(f"Download complete... {filename}")

download_yt_as_mp3("taiwan", "lVigbXHejWA","hard-work-will-win")