How to Download & Merge YouTube Videos in High Quality with Python
Want to download YouTube videos in 1080p, 1440p, or even 4K with the best audio quality?
By default, YouTube separates high-resolution video and audio streams.
In this tutorial, you’ll learn how to use Python with pytubefix
+ moviepy
to
download and merge video + audio into one MP4 — without quality loss.
Step 1: Install Required Python Modules
Make sure you have Python 3.8+ installed. Then open your terminal (or command prompt) and run:
pip install pytubefix
This will install:
- pytubefix → a reliable fork of pytube for downloading YouTube videos.
pip install moviepy==1.0.3
This will install:
- moviepy → to merge video & audio streams into a final MP4. ๐ Get Full MoviePy Installation Tutorial
Step 2: Full Python Script
Copy and paste the following code into a file called yt_downloader.py
:
import os
from pytubefix import YouTube
from pytubefix.cli import on_progress
from moviepy.editor import VideoFileClip, AudioFileClip
# ------------ Input URL (cleaned) ------------
raw_url = " Your Youtube Video Url"
if "?" in raw_url:
raw_url = raw_url.split("?")[0]
# ------------ Create YouTube object ------------
yt = YouTube(raw_url, on_progress_callback=on_progress)
print("\n๐ฌ Title :", yt.title)
print("๐ค Author:", yt.author)
print(f"⏱️ Length: {yt.length // 60} min {yt.length % 60} sec\n")
# ------------ Preferred Resolutions in Order ------------
preferred_res = ["1080p", "720p", "360p"]
# You can extend this:
# preferred_res = ["2160p", "1440p", "1080p", "720p", "480p", "360p", "240p", "144p"]
video_stream = None
for res in preferred_res:
video_stream = yt.streams.filter(adaptive=True, only_video=True, file_extension="mp4", res=res).first()
if video_stream:
print(f"✅ Selected VIDEO resolution: {res}")
break
video_filename, audio_filename = None, None
# ------------ Download VIDEO ------------
if video_stream:
try:
video_filename = f"{yt.title}_VIDEO_ONLY_{video_stream.resolution}.mp4"
video_stream.download(filename=video_filename)
print(f"๐ฅ Downloaded video as: {video_filename}")
except Exception as e:
print(f"❌ Video download error: {e}")
else:
print("❌ No suitable video stream found!")
# ------------ Download AUDIO ------------
audio_stream = yt.streams.filter(adaptive=True, only_audio=True, file_extension="mp4").order_by("abr").desc().first()
if audio_stream:
try:
audio_filename = f"{yt.title}_AUDIO_ONLY_{audio_stream.abr}.mp4"
audio_stream.download(filename=audio_filename)
print(f"๐ง Downloaded audio as: {audio_filename}")
except Exception as e:
print(f"❌ Audio download error: {e}")
else:
print("❌ No audio stream found!")
# ------------ Merge VIDEO + AUDIO ------------
if video_filename and audio_filename:
print("\n๐ฌ Merging video + audio...")
video = VideoFileClip(video_filename)
audio = AudioFileClip(audio_filename)
final_video = video.set_audio(audio)
final_output = "merged_final.mp4"
final_video.write_videofile(
final_output,
codec="libx264",
audio_codec="aac",
bitrate="5000k",
audio_bitrate="192k",
preset="ultrafast",
threads=4
)
video.close()
audio.close()
final_video.close()
# ------------ Cleanup Temp Files ------------
try:
os.remove(video_filename)
os.remove(audio_filename)
print("๐งน Removed temporary video/audio files.")
except Exception as e:
print(f"⚠️ Cleanup error: {e}")
print(f"\n✅ Final merged file saved as: {final_output}")
else:
print("\n❌ Could not merge. Missing video or audio file.")
Step 3: Run the Script
Navigate to the folder where you saved yt_downloader.py
and run:
python yt_downloader.py
Example Output
๐ฌ Title : Python Tutorial for Beginners
๐ค Author: Code Academy
⏱️ Length: 12 min 34 sec
✅ Selected VIDEO resolution: 1080p
๐ฅ Downloaded video as: Python Tutorial_VIDEO_ONLY_1080p.mp4
๐ง Downloaded audio as: Python Tutorial_AUDIO_ONLY_160kbps.mp4
๐ฌ Merging video + audio...
Moviepy - Building video merged_final.mp4.
Moviepy - Done !
๐งน Removed temporary video/audio files.
✅ Final merged file saved as: merged_final.mp4
Practical Tips
- Always update
pytubefix
regularly (pip install -U pytubefix
) for YouTube compatibility. - Use
2160p
inpreferred_res
if you want 4K videos. - Change bitrate (
2000k
) if you want smaller file size for 720p. - For automation, wrap this code into a
download_youtube()
function.
With this script, you no longer need online downloaders. Python gives you full control over quality, merging, and file size. ๐ Start using this method today to download YouTube videos in the best quality possible!