Search code examples
pythonffmpegsplit

Split a video with ffmpeg, without reencoding, at timestamps given in a txt file


Let's say we have a video input.mp4, and a file split.csv containing:

start;end;name
00:00:27.132;00:07:42:422;"Part A.mp4"
00:07:48.400;00:17:17.921;"Part B.mp4"

(or I could format the text file in any other format)

How to split the MP4 into different parts with the given start / end timestamps, and the given filename for each part?

Is it possible directly with ffmpeg, and if not with a Python script?


Solution

  • I finally found a working answer:

    import csv, subprocess
    INPUT_FILE = "input.mp4"
    CSV_FILE = "split.csv"
    FFMPEG_PATH = r"D:\misc\ffmpeg.exe"
    with open(CSV_FILE, 'r') as f:
        reader = csv.DictReader(f, delimiter=';')
        for row in reader:
            start = row['start']
            end = row['end']
            output_file = row['name']
            start_time = sum(float(x) * 60 ** i for i, x in enumerate(reversed(start.split(":"))))
            end_time = sum(float(x) * 60 ** i for i, x in enumerate(reversed(end.split(":"))))
            duration = end_time - start_time
            output_file = output_file.replace("'", "\'")
            output_file = f"{output_file}.mp4"
            command = [FFMPEG_PATH, '-y', '-i', INPUT_FILE, '-ss', start, '-t', str(duration), '-vcodec', 'copy', '-acodec', 'copy', output_file]
            subprocess.run(command)
    

    Note that it's important to escape output_file to avoid having ' in it.