python – How to automate ffmpeg to split and merge parts of video, and keep the audio in sync?

I have a Python script that automates trimming a large video (2 hours) into smaller segments and then concatenating them without re-encoding, to keep the process fast. The script runs these ffmpeg commands:

import subprocess

# Extract chunks
segments = [(0, 300), (300, 600), (600, 900)]  # example segments in seconds
for i, (start, length) in enumerate(segments):
    subprocess.run([
        "ffmpeg", "-i", "input.mp4", "-ss", str(start), "-t", str(length),
        "-c", "copy", "-reset_timestamps", "1", "-y", f"chunk_{i}.mp4"
    ], check=True)

# Create concat list
with open("list.txt", "w") as f:
    for i in range(len(segments)):
        f.write(f"file 'chunk_{i}.mp4'\n")

# Concatenate
subprocess.run([
    "ffmpeg", "-f", "concat", "-safe", "0",
    "-i", "list.txt", "-c", "copy", "-y", "merged_output.mp4"
], check=True)

All chunks come from the same source video, with identical codecs, resolution, and bitrate. Despite this, the final merged_output.mp4 sometimes has audio out of sync—especially after the first chunk.

I’ve tried using -ss before -i to cut on keyframes, but the issue persists.

Question: How can I ensure correct A/V sync in the final concatenated video when programmatically segmenting and merging via ffmpeg without fully re-encoding? Is there a way to adjust the ffmpeg commands or process to avoid audio desynchronization?

Read more here: Source link