Here's a Python script that concatenates MP4 files in alphabetical order using FFmpeg:
import os
import subprocess
import fnmatch
def concatenate_videos(output_filename='output.mp4'):
# Get all MP4 files in current directory and sort them
files = sorted(fnmatch.filter(os.listdir('.'), '*.mp4'))
if not files:
print("Error: No MP4 files found in the current directory.")
return
try:
# Create temporary text file listing all video files
with open('files_to_concatenate.txt', 'w') as filelist:
for video_file in files:
filelist.write(f"file '{video_file}'\n")
# Run FFmpeg command to concatenate videos
subprocess.run([
'ffmpeg',
'-f', 'concat',
'-safe', '0', # Allow absolute filepaths if needed
'-i', 'files_to_concatenate.txt',
'-c', 'copy',
output_filename
], check=True)
print(f"Videos successfully concatenated to {output_filename}")
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
print("Ensure FFmpeg is installed and added to system PATH.")
finally:
# Clean up temporary file
if os.path.exists('files_to_concatenate.txt'):
os.remove('files_to_concatenate.txt')
if __name__ == "__main__":
concatenate_videos()
To use this script:
-
Ensure FFmpeg is installed on your system:
-
Place this script in the same directory as your MP4 files
-
Run the script:
python concatenate_videos.py
This will:
- Automatically detect all MP4 files in the current directory
- Sort them alphabetically
- Concatenate them using FFmpeg
- Save the result as
output.mp4
Requirements:
- Python 3.6+
- FFmpeg installed and in system PATH
Note: This requires all videos to have the same:
- Video codec
- Audio codec
- Frame rate
- Resolution
If these differ, you'll need to re-encode the videos first (this script uses -c copy for fast concatenation without re-encoding). For incompatible files, you would need to modify the FFmpeg command to include encoding parameters.