In this article, we will explore a Python script that leverages the pytube
and moviepy
libraries to automate the process of downloading YouTube videos, cutting random 5-second segments, and concatenating them into a single output video. This script is not only a demonstration of the capabilities of Python in video processing but also a practical example of how automation can simplify complex tasks.
In this project, I am cutting and merging 5 seconds each from a list of videos. Feel free to improve the code to your needs. Supposing you know the exact timestamp of each video, you could edit the seconds in the script.
Installation
Before diving into the script, make sure you have the necessary Python libraries installed. You can install them using the following commands:
pip install pytube
pip install moviepy
Additionally, ensure you have the required dependencies for moviepy
. You may need to install FFmpeg:
pip install ffmpeg-python
This is the link to the source code: Download source code. If you have cloned the source code, you can install the dependencies by running this command:
pip install -r requirements.txt
Code Overview
Now, let's break down the provided Python script.
import os
from pytube import YouTube
from moviepy.editor import VideoFileClip, concatenate_videoclips
import random
# Output directory for downloaded videos
output_dir = 'C:\\Users\\dell\\Videos\\output_videos'
# Create the output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# List of YouTube video links
youtube_links = [
"https://www.youtube.com/watch?v=example_video_id"
]
# Download YouTube videos
downloaded_files = []
for link in youtube_links:
try:
yt = YouTube(link)
video = yt.streams.filter(file_extension="mp4", res="720p").first()
downloaded_file = video.download(output_dir)
downloaded_files.append(downloaded_file)
except Exception as e:
print(f"Error downloading video from {link}: {e}")
# Cut random 5 seconds from each downloaded video (excluding the first 20 seconds)
cut_videos = []
for file_path in downloaded_files:
try:
video_clip = VideoFileClip(file_path)
start_time = random.uniform(20, max(20, video_clip.duration - 5))
cut_clip = video_clip.subclip(start_time, start_time + 5)
cut_videos.append(cut_clip)
except Exception as e:
print(f"Error processing video file {file_path}: {e}")
# Concatenate the cut videos into one final output
final_output = concatenate_videoclips(cut_videos)
# Set the output file path
output_path = os.path.join(output_dir, "final_output.webm")
# Write the final output to file
final_output.write_videofile(output_path, codec="libvpx", audio_codec="libvorbis", bitrate="8M", remove_temp=True)
# Print information about the final output
print(f"Final output saved at: {output_path}")
print(f"Total duration of the final output: {final_output.duration} seconds")
Code Explanation
1. Output Directory Setup
The script begins by setting up the output directory for the downloaded and processed videos.
2. YouTube Video Links
You should replace the placeholder link in the youtube_links
list with the actual YouTube video link you want to process.
3. Download YouTube Videos
The script utilizes the pytube
library to download YouTube videos. It filters for videos with the file extension "mp4" and a resolution of "720p."
4. Cut Random 5-Second Segments
For each downloaded video, a random 5-second segment is cut (excluding the first 20 seconds). This introduces variety and randomness to the final output.
5. Concatenate Videos
The cut video segments are then concatenated into a single output video using moviepy
's concatenate_videoclips
function.
6. Set Output Path and Write to File
The final concatenated video is written to a specified output file path in WebM format.
7. Print Output Information
Finally, the script prints information about the saved output, including the file path and total duration.
Use Cases
This script can be adapted for various use cases, such as creating highlight reels from multiple videos, generating personalized content, or automating the creation of video compilations.