Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pytubefix import YouTube
- from moviepy.editor import *
- import sys
- import os
- def get_best_1080p_stream(streams):
- # Filter streams for 1080p or lower
- filtered_streams = streams.filter(adaptive=True,
- file_extension='mp4',
- only_video=True,
- resolution="1080p")
- # If no 1080p stream is found, get the next best quality below 1080p
- if not filtered_streams:
- filtered_streams = streams.filter(adaptive=True,
- file_extension='mp4',
- only_video=True)\
- .order_by('resolution')\
- .desc()
- # Filter out streams above 1080p
- filtered_streams = [s for s in filtered_streams if not s.resolution or
- int(s.resolution[:-1]) <= 1080]
- return filtered_streams[0] if filtered_streams else None
- def download_video(url):
- try:
- yt = YouTube(url)
- print(f"Title: {yt.title}")
- print("Starting download...")
- # Get the best video stream at 1080p or lower
- video_stream = get_best_1080p_stream(yt.streams)
- if not video_stream:
- print("Error: No suitable video stream found")
- sys.exit(1)
- # Get the highest quality audio stream
- audio_stream = yt.streams.filter(only_audio=True)\
- .order_by('abr')\
- .desc()\
- .first()
- if video_stream and audio_stream:
- print(f"Selected video quality: {video_stream.resolution}")
- print(f"Selected audio quality: {audio_stream.abr}")
- # Create temporary filenames
- temp_video_path = 'temp_video2.mp4'
- temp_audio_path = 'temp_audio2.mp4'
- # Download both streams
- print(f"Downloading video...")
- video_stream.download(filename=temp_video_path)
- print(f"Downloading audio...")
- audio_stream.download(filename=temp_audio_path)
- # Prepare the final filename
- final_path = f"{yt.title}.mp4"
- # Remove invalid characters from filename
- final_path = "".join(c for c in final_path if c.isalnum() or c in (' ', '-', '_', '.'))
- print("Merging video and audio...")
- # Combine video and audio using moviepy
- video_clip = VideoFileClip(temp_video_path)
- audio_clip = AudioFileClip(temp_audio_path)
- final_clip = video_clip.set_audio(audio_clip)
- final_clip.write_videofile(final_path, codec='libx264', audio_codec='aac')
- # Clean up
- video_clip.close()
- audio_clip.close()
- os.remove(temp_video_path)
- os.remove(temp_audio_path)
- print(f"Download completed: {final_path}")
- except Exception as e:
- print(f"Error: Failed to download video: {str(e)}")
- sys.exit(1)
- if __name__ == "__main__":
- if len(sys.argv) != 2:
- print("Usage: python script.py <youtube_url>")
- sys.exit(1)
- url = sys.argv[1]
- download_video(url)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement