DEV Community

Trix Cyrus
Trix Cyrus

Posted on

Making YouTube Videos Downloader Using Python(mp3 and mp4)

Author: Trix Cyrus

Why Download YouTube Videos with Python?

There are many reasons why you might want to download YouTube videos programmatically:

-For offline viewing.
-To extract audio for personal use.
-For educational purposes, such as analyzing or editing video content.
~ With Python, downloading videos becomes a simple, automated task.

Lets Get Started

Step 1: Install pytube and moviepy

First, you’ll need to install the pytube and moviepy library, which is a lightweight Python library for downloading YouTube videos in both p3 and mp4.

pip install pytube moviepy

Enter fullscreen mode Exit fullscreen mode

then,

nano downloader.py
Enter fullscreen mode Exit fullscreen mode
Step 2: Writing the Python Script.
Enter fullscreen mode Exit fullscreen mode

paste the below script in that file.

from pytube import YouTube
import moviepy.editor as mp
import os

def download_youtube_video(url, file_format):
    try:
        # Fetch the YouTube video
        yt = YouTube(url)
        stream = yt.streams.filter(only_audio=(file_format == 'mp3')).first() if file_format == 'mp3' else yt.streams.get_highest_resolution()

        print(f"Downloading {file_format.upper()}...")
        output_path = stream.download()

        if file_format == 'mp3':
            output_mp3 = output_path.replace(".mp4", ".mp3")
            print("Converting to MP3...")
            video_clip = mp.AudioFileClip(output_path)
            video_clip.write_audiofile(output_mp3)
            video_clip.close()
            os.remove(output_path)  # Remove the temporary video file

        print(f"\nDownload completed in {file_format.upper()} format!")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    print("YouTube to MP3/MP4 Downloader")

    url = input("Enter the YouTube video URL: ").strip()

    file_format = input("Do you want to download as MP3 or MP4? (Enter 'mp3' or 'mp4'): ").strip().lower()

    if file_format not in ['mp3', 'mp4']:
        print("Invalid format. Please enter 'mp3' or 'mp4'.")
    else:
        download_youtube_video(url, file_format)
Enter fullscreen mode Exit fullscreen mode

Save the file and run

python downloader.py
Enter fullscreen mode Exit fullscreen mode

Then It will prompt to enter url and output format i.e. mp3 or mp4.

comment if any issue or error occur.

And All Set

~TrixSec

Top comments (0)