Denizhalil

Downloading YouTube Videos in High Quality With Python

Introduction

YouTube is one of the most popular platforms globally, providing billions of video contents that cater to users’ information and entertainment needs. However, in some situations, users may want to watch these videos offline. In this article, we will explain how to download YouTube videos in high quality and merge video and audio files using the Python programming language.

Learning Objectives

By the end of this article, you will learn:

  1. How to download YouTube videos and audio files using Python.
  2. How to merge video and audio files.
  3. How to clean up temporary files.
  4. How to create modular projects using class-based programming in Python.

Project Objective

The objective of this project is to enable users to download YouTube videos and audio files separately using Python, and then merge these files into a single high-quality file. This process involves using the pytube library for downloading video and audio files, and the moviepy library for merging these files.

Let’s Start Coding

First, you need to install the required libraries:

$ pip install pytube moviepy

Then, use the following code to create our project:

Importing the Required Libraries

from pytube import YouTube
from moviepy.editor import VideoFileClip, AudioFileClip
import os
import re

In this section, we import the libraries we will use in the project. pytube is used for downloading YouTube videos, while moviepy is used for merging video and audio files. The os module is used for file operations, and the re module is used to clean invalid characters from file names(File Encryption and Decryption for Data Security).

Amazon Product
Programming Symbols Stickers

Our editor’s recommendation

Machine Learning with PyTorch and Scikit-Learn: Develop machine learning and deep learning models with Python

-35% $33.86 on Amazon

Defining the YouTubeDownloader Class

class YouTubeDownloader:
    def __init__(self, url, output_path='downloads'):
        self.url = url
        self.output_path = output_path
        self.video_path = None
        self.audio_path = None
        if not os.path.exists(self.output_path):
            os.makedirs(self.output_path)

This class is used to download and merge YouTube videos and audio files. The __init__ method takes the necessary parameters such as URL and output directory when the class is instantiated, and creates the output directory if it does not exist.

Cleaning File Names

  def sanitize_filename(self, filename):
          return re.sub(r'[\\/*?:"<>|]', "", filename)

This method cleans invalid characters from file names and returns a valid file name.

Downloading Video

    def download_video(self):
        yt = YouTube(self.url)
        title = self.sanitize_filename(yt.title)
        video_stream = yt.streams.filter(only_video=True, file_extension='mp4').order_by('resolution').desc().first()
        self.video_path = os.path.join(self.output_path, f"{title}_video.mp4")
        video_stream.download(output_path=self.output_path, filename=f"{title}_video.mp4")
        print(f"Video downloaded to {self.video_path}")

This method downloads only the video stream from the specified URL. The path of the downloaded video file is saved to the self.video_path variable.

Downloading Audio

    def download_audio(self):
        yt = YouTube(self.url)
        title = self.sanitize_filename(yt.title)
        audio_stream = yt.streams.filter(only_audio=True).first()
        self.audio_path = os.path.join(self.output_path, f"{title}_audio.mp4")
        audio_stream.download(output_path=self.output_path, filename=f"{title}_audio.mp4")
        print(f"Audio downloaded to {self.audio_path}")

This method downloads only the audio stream from the specified URL. The path of the downloaded audio file is saved to the self.audio_path variable.

Amazon Product
Programming Symbols Stickers Programming Symbols Stickers Programming Symbols Stickers

Programming Symbols Stickers 50Pcs

Waterproof, Removable, Cute, Beautiful, Stylish Teen Stickers, Suitable for Boys and Girls in Water Bottles, Phones, Suitcase Vinyl

$5.59 on Amazon

Merging Video and Audio

    def combine_video_audio(self):
        if self.video_path and self.audio_path:
            video_clip = VideoFileClip(self.video_path)
            audio_clip = AudioFileClip(self.audio_path)

            final_clip = video_clip.set_audio(audio_clip)
            final_output_path = os.path.join(self.output_path, f"{os.path.splitext(os.path.basename(self.video_path))[0]}_final.mp4")
            final_clip.write_videofile(final_output_path, codec='libx264', audio_codec='aac')
            print(f"Final video with audio saved to {final_output_path}")

            os.remove(self.video_path)
            os.remove(self.audio_path)
            print("Temporary files removed.")
        else:
            print("Video or audio file is missing. Please download both before combining.")

This method merges the downloaded video and audio files and saves the result to final_output_path. After the process is completed, it removes the temporary video and audio files.

Starting the Download and Merge Process

    def download_and_combine(self):
        self.download_video()
        self.download_audio()
        self.combine_video_audio()

This method first downloads the video, then the audio, and finally merges these files.

Amazon Product
Programming Symbols Stickers Programming Symbols Stickers Programming Symbols Stickers

Cyber Security Coffee Mug

Cyber Security Coffee Mug 15oz Black -I’m Cybersecurity Expert – Hacker IT Security Software Engineering Programmer Coder IT Analyst Network Engineer Computer Engineer.

$19.99 on Amazon
if __name__ == '__main__':
    url = input('Enter the link you want to download: ')
    downloader = YouTubeDownloader(url)
    downloader.download_and_combine()

This section takes the YouTube link from the user and starts the download and merge process.

Conclusion

In this article, we learned the basic steps of downloading and merging YouTube videos and audio files using Python. By leveraging the power of the pytube and moviepy libraries, you can easily download and merge high-quality videos. Projects like these can be performed very efficiently and effectively due to Python’s flexibility and rich library ecosystem. You can develop your own projects based on this example and customize them according to your different needs.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.