Thursday, 31 July 2025

How to Split an MP4 File into 2-Minute Segments Using Python

If you’ve ever worked with large MP4 video files, you might have run into issues with uploading limits or processing performance. Splitting a video into smaller, evenly timed chunks—such as 2-minute segments—can make editing and sharing much easier. In this tutorial, we’ll use Python and the MoviePy library to automate the process.

What You'll Need

  • Python 3 installed
  • MoviePy library: pip install moviepy
  • An MP4 file you'd like to split

How It Works

The script loads your MP4 file, calculates the duration, and slices it into 2-minute segments using MoviePy’s subclip function. Each chunk is saved as a new video file.

Python Script to Split the MP4


from moviepy.editor import VideoFileClip
import math
import os

def split_video(file_path, chunk_duration=120):
    video = VideoFileClip(file_path)
    video_duration = int(video.duration)  # in seconds
    total_chunks = math.ceil(video_duration / chunk_duration)
    
    base_name = os.path.splitext(os.path.basename(file_path))[0]
    output_dir = f"{base_name}_chunks"
    os.makedirs(output_dir, exist_ok=True)

    print(f"Total Duration: {video_duration} seconds")
    print(f"Splitting into {total_chunks} segments of {chunk_duration} seconds each...")

    for i in range(total_chunks):
        start = i * chunk_duration
        end = min(start + chunk_duration, video_duration)
        subclip = video.subclip(start, end)
        output_path = os.path.join(output_dir, f"{base_name}_part{i+1}.mp4")
        subclip.write_videofile(output_path, codec="libx264", audio_codec="aac")
        print(f"Saved: {output_path}")

    print("Splitting completed.")

# Example usage
split_video("your_video.mp4", chunk_duration=120)
  

Output

After running the script, you’ll get a folder named after your video (e.g., my_video_chunks) containing files like:

  • my_video_part1.mp4
  • my_video_part2.mp4
  • ...

Tips

  • For longer or shorter segments, just change the chunk_duration parameter.
  • Ensure your MP4 file is not corrupted and properly encoded with audio.

No comments:

Post a Comment