2 min read

Video Format Converter

This utility converts video files from one format to another (e.g., MP4 to GIF, AVI to MP4) using the moviepy library. It supports resizing and sub-clipping during conversion.

Modules Used:

  • moviepy: For video editing and processing.
  • argparse: To handle command-line arguments.

Installation

pip install moviepy

The Code

Save this as converter.py.

from moviepy.editor import VideoFileClip
import argparse
import os
import sys

def convert_video(input_file, output_file, start_time=None, end_time=None, resize=None):
    if not os.path.exists(input_file):
        print(f"Error: Input file '{input_file}' not found.")
        return

    try:
        print(f"Loading {input_file}...")
        clip = VideoFileClip(input_file)

        # Optional: Subclip (Trim)
        if start_time is not None or end_time is not None:
            # Handle defaults if only one is provided
            s = start_time if start_time is not None else 0
            e = end_time if end_time is not None else clip.duration
            print(f"Trimming video from {s}s to {e}s...")
            clip = clip.subclip(s, e)

        # Optional: Resize
        if resize:
            print(f"Resizing video (scale factor: {resize})...")
            clip = clip.resize(resize)

        print(f"Converting to {output_file}...")

        # Determine output format based on extension
        ext = os.path.splitext(output_file)[1].lower()

        if ext == '.gif':
            clip.write_gif(output_file)
        elif ext == '.mp3':
            clip.audio.write_audiofile(output_file)
        else:
            # Default video write
            # codec='libx264' is standard for MP4
            clip.write_videofile(output_file, codec='libx264')

        print("Conversion complete!")

    except Exception as e:
        print(f"Error: {e}")
    finally:
        # Close the clip to release resources
        if 'clip' in locals():
            clip.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Video Format Converter")
    parser.add_argument("input", help="Input video file")
    parser.add_argument("output", help="Output file (extension determines format, e.g., .mp4, .gif, .mp3)")
    parser.add_argument("--start", type=float, help="Start time in seconds (for trimming)")
    parser.add_argument("--end", type=float, help="End time in seconds (for trimming)")
    parser.add_argument("--resize", type=float, help="Resize factor (e.g., 0.5 for half size)")

    args = parser.parse_args()

    convert_video(args.input, args.output, args.start, args.end, args.resize)

Usage

# Convert AVI to MP4
python converter.py input.avi output.mp4

# Convert video to GIF (first 5 seconds, resized to 50%)
python converter.py video.mp4 animation.gif --start 0 --end 5 --resize 0.5

# Extract audio to MP3
python converter.py video.mp4 audio.mp3

programming/python/python