Skip to content

Instantly share code, notes, and snippets.

@ClimenteA
Created June 10, 2023 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClimenteA/b1a6a803e822e222798d1e7319d1cddc to your computer and use it in GitHub Desktop.
Save ClimenteA/b1a6a803e822e222798d1e7319d1cddc to your computer and use it in GitHub Desktop.
Concat with FFmpeg videos from a folder
import os
# Assuming video files are in this format: "1.mp4"
filepaths = [f for f in os.listdir() if f.endswith(".mp4")]
sorted_filepaths = sorted(filepaths, key=lambda val: int(val.split(".")[0]))
allvids = [f'file {os.path.abspath(f)}' for f in sorted_filepaths]
with open("vids.txt", "w") as f:
f.write("\n".join(allvids))
# cat vids.txt
os.system("ffmpeg -f concat -safe 0 -i vids.txt -c copy curs_programare.mp4")
@ClimenteA
Copy link
Author

Another option:

import os
import subprocess

input_folder = "./reencoded"
output_file = "curs_programare.mp4"

# Get a list of all the .mp4 files in the input folder
input_files = [
    file for file in os.listdir(input_folder) if file.lower().endswith(".mp4")
]

input_files = sorted(input_files, key=lambda val: int(val.split(".")[0]))

# Create a temporary file to store the list of input files
with open("input_list.txt", "w") as f:
    for input_file in input_files:
        f.write(f"file '{os.path.join(input_folder, input_file)}'\n")
        
# FFmpeg command for concatenating the files
ffmpeg_cmd = [
    "ffmpeg",
    "-f", "concat",
    "-safe", "0",
    "-i", "input_list.txt",
    "-c", "copy",
    "-movflags", "+faststart",
    output_file,
]

# Run the FFmpeg command
subprocess.run(ffmpeg_cmd)

# Remove the temporary input file list
os.remove("input_list.txt")

print("Concatenation complete!")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment