Skip to content

Instantly share code, notes, and snippets.

@MatthewGlenn
Last active June 26, 2024 19:54
Show Gist options
  • Save MatthewGlenn/8c9962e97b4d75661b3ce9e9afdaf01c to your computer and use it in GitHub Desktop.
Save MatthewGlenn/8c9962e97b4d75661b3ce9e9afdaf01c to your computer and use it in GitHub Desktop.
Combine all videos in a folder using ffmpeg and python
import subprocess
import os
# Attempt to import prompt_toolkit for enhanced input functionality
try:
from prompt_toolkit import prompt
from prompt_toolkit.completion import PathCompleter
prompt_toolkit_available = True
except ImportError:
prompt_toolkit_available = False
def get_input(prompt_message, path_completion=False):
if prompt_toolkit_available and path_completion:
return prompt(prompt_message, completer=PathCompleter())
else:
return input(prompt_message)
# Use the get_input function for user input
input_folder = get_input("Folder with videos to combine: ", path_completion=True)
output_file_path = get_input("Combined video file path (including filename and extension): ", path_completion=True)
# Ensure the output folder exists
output_folder = os.path.dirname(output_file_path)
if output_folder:
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Check if the input folder exists
if not os.path.exists(input_folder):
print("Input folder does not exist.")
exit()
# Get a list of all the files in the input folder
input_files = [os.path.join(input_folder, file) for file in sorted(os.listdir(input_folder))]
# Construct the ffmpeg command
command = ["ffmpeg"]
for file in input_files:
command.extend(["-i", file])
command.append("-filter_complex")
command.append("[0:v] [0:a] [1:v] [1:a] concat=n={}:v=1:a=1 [v] [a]".format(len(input_files)))
command.extend(["-map", "[v]", "-map", "[a]", output_file_path])
# Execute the command
subprocess.run(command)

Combine Videos with FFmpeg and Python

This script allows you to combine multiple videos into a single video using FFmpeg and Python.

Dependencies

  • Python
  • FFmpeg

Optional Enhancement

  • Prompt_Toolkit
    • Used to show file path options, installed with pip install prompt_toolkit
    • If you do not import it, the script will still run.

Usage

  1. Place the videos you wish to combine in a folder.
  2. Run the python script with python combine_videos.py.
  3. When prompted, provide the folder path with the videos you wish to combine and the file path for the combined video.

Example Usage

Windows:

python .\combine_videos.py
Folder with videos to combine: sampleVideos
Combined video file path (including filename and extension): outputVideos/combinedVideo.mkv

macOS & Linux:

python3 combine_videos.py
Folder with videos to combine: sampleVideos
Combined video file path (including filename and extension): outputVideos/combinedVideo.mkv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment