Your issue occurs because get_highest_resolution()
only downloads progressive streams, which contain both video and audio but are limited in resolution. The highest-quality videos on YouTube are available only as separate video and audio streams (adaptive streaming).
To get the best quality, you need to download the video and audio separately and merge them using ffmpeg
. Here’s the fixed version of your code:
from pytubefix import YouTube
import subprocess
video_url = "https://youtu.be/NI9LXzo0UY0?si=_Jy_CzN-QwI4SOkC"
def Download(link):
youtube_object = YouTube(link)
# Get highest quality video and audio separately
video_stream = youtube_object.streams.filter(adaptive=True, file_extension="mp4", only_video=True).order_by("resolution").desc().first()
audio_stream = youtube_object.streams.filter(adaptive=True, file_extension="mp4", only_audio=True).order_by("abr").desc().first()
if not video_stream or not audio_stream:
print("No suitable streams found.")
return
# Define output filenames
video_file = "video_temp.mp4"
audio_file = "audio_temp.mp4"
output_file = "final_video.mp4"
# Download video and audio separately
video_stream.download(filename=video_file)
audio_stream.download(filename=audio_file)
# Merge using ffmpeg
ffmpeg_command = ["ffmpeg", "-y", "-i", video_file, "-i", audio_file, "-c", "copy", output_file]
subprocess.run(ffmpeg_command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("Download completed: " + output_file)
Download(video_url)
Downloads the highest quality video and audio separately instead of a low-quality combined stream.
Uses ffmpeg
to merge them, preserving quality without re-encoding.
ffmpeg
Since YouTube provides high-quality video and audio separately, ffmpeg
is required to merge them. Install it via:
Windows: Download from https://ffmpeg.org and add it to PATH
.
Linux/macOS: Run sudo apt install ffmpeg
(Debian/Ubuntu) or brew install ffmpeg
(Mac).
Now, you’ll always get the best quality available!