To concatenate a collection of .mp4 files located in the current working directory in alphabetical order, we can use the powerful command-line tool ffmpeg, which is widely used for multimedia processing. The approach involves:
Listing all .mp4 files in the current directory.
Sorting them alphabetically.
Creating a input.txt file that tells ffmpeg which files to concatenate.
Using ffmpeg to perform the concatenation.
✅ Prerequisites
Before running the script, ensure that ffmpeg is installed on your system and accessible from the command line. You can install it via:
This script assumes all .mp4 files are in the current working directory.
The output will be saved as output.mp4 in the same directory.
If the files have different codecs, ffmpeg will automatically re-encode them, which may take longer but ensures compatibility.
📜 Python Code
python
import os
import subprocess
def concatenate_mp4_files():
# Step 1: List all .mp4 files in the current directory
files = []
for f in os.listdir('.'):
if os.path.isfile(f) and f.lower().endswith('.mp4'):
files.append(f)
# Step 2: Sort the files alphabetically
files.sort()
if not files:
print("No .mp4 files found in the current directory.")
return
# Step 3: Create the input text file for ffmpeg
input_file = 'input.txt'
with open(input_file, 'w') as f:
for file in files:
f.write(f"file '{file}'\n")
# Step 4: Run ffmpeg to concatenate the files
try:
print("Starting video concatenation...")
subprocess.run(
['ffmpeg', '-f', 'concat', '-i', input_file, 'output.mp4'],
check=True
)
print("Concatenation completed successfully.")
except subprocess.CalledProcessError as e:
print(f"An error occurred during concatenation: {e}")
finally:
# Optional: Clean up the input.txt file
if os.path.exists(input_file):
os.remove(input_file)
print("Temporary file 'input.txt' has been removed.")
if __name__ == "__main__":
concatenate_mp4_files()
📝 Example Usage
Assume the following .mp4 files are in the current directory:
code
video1.mp4
video2.mp4
video3.mp4
Running the script will create output.mp4, which is the concatenation of the three videos in alphabetical order.
🔄 Optional Enhancements
Allow the user to specify an input directory.
Add progress tracking or logging.
Support for other video formats (e.g., .avi, .mkv).
Handle duplicate files or invalid inputs gracefully.
This script provides a clean and robust way to concatenate MP4 files using Python and ffmpeg, ensuring compatibility and ease of use.
User
how about doing the same for mp3 audio files?
Assistant
To concatenate a collection of .mp3 audio files in alphabetical order, you can use a similar approach to the one used for .mp4 files, leveraging the ffmpeg tool. The process involves:
Listing all .mp3 files in the current directory.
Sorting them alphabetically.
Creating an input.txt file that tells ffmpeg which files to concatenate.
Using ffmpeg to perform the concatenation.
✅ Prerequisites
Ensure ffmpeg is installed and accessible from the command line. You can install it via:
This script assumes all .mp3 files are in the current working directory.
The output will be saved as output.mp3 in the same directory.
If the MP3 files have different audio parameters (bitrate, sample rate, etc.), ffmpeg will re-encode them, which may take longer but ensures compatibility.
import os
import subprocess
def concatenate_mp3_files():
# Step 1: List all .mp3 files in the current directory
files = []
for f in os.listdir('.'):
if os.path.isfile(f) and f.lower().endswith('.mp3'):
files.append(f)
# Step 2: Sort the files alphabetically
files.sort()
if not files:
print("No .mp3 files found in the current directory.")
return
# Step 3: Create the input text file for ffmpeg
input_file = 'input.txt'
with open(input_file, 'w') as f:
for file in files:
f.write(f"file '{file}'\n")
# Step 4: Run ffmpeg to concatenate the files
try:
print("Starting audio concatenation...")
subprocess.run(
['ffmpeg', '-f', 'concat', '-i', input_file, '-c', 'copy', 'output.mp3'],
check=True
)
print("Concatenation completed successfully.")
except subprocess.CalledProcessError as e:
print(f"An error occurred during concatenation: {e}")
finally:
# Optional: Clean up the input.txt file
if os.path.exists(input_file):
os.remove(input_file)
print("Temporary file 'input.txt' has been removed.")
if __name__ == "__main__":
concatenate_mp3_files()
📝 Example Usage
Assume the following .mp3 files are in the current directory:
code
song1.mp3
song2.mp3
song3.mp3
Running the script will create output.mp3, which is the concatenation of the three audio files in alphabetical order.
🔄 Optional Enhancements
Allow the user to specify an input directory.
Add progress tracking or logging.
Support for other audio formats (e.g., .wav, .ogg).
Handle duplicate files or invalid inputs gracefully.
Add an option to re-encode audio with specific parameters (e.g., bitrate, sample rate).
This script provides a clean and robust way to concatenate MP3 files using Python and ffmpeg, ensuring compatibility and ease of use.