Skip to content

Instantly share code, notes, and snippets.

@xjasonlyu
Last active December 6, 2024 22:39
Show Gist options
  • Select an option

  • Save xjasonlyu/9d8ab7f0265b28cbe799929b1997dc40 to your computer and use it in GitHub Desktop.

Select an option

Save xjasonlyu/9d8ab7f0265b28cbe799929b1997dc40 to your computer and use it in GitHub Desktop.
import sys
import os
import subprocess
import tempfile
from argparse import ArgumentParser
def generate_input_file(video_files: list[str]) -> str:
with tempfile.NamedTemporaryFile(
mode="w",
delete=False,
suffix=".txt",
) as temp_input_file:
try:
for video in video_files:
temp_input_file.write(
f"file '{os.path.abspath(video)}'\n",
)
return temp_input_file.name
except Exception as e:
print(f"Error writing to temporary input file: {e}")
sys.exit(1)
def concat_videos(video_files, output_file):
# Generate temporary input file.
input_file = generate_input_file(video_files)
# Build ffmpeg command line.
ffmpeg_command = [
"ffmpeg",
"-safe", "0",
"-f", "concat",
"-i", input_file,
"-c", "copy",
output_file
]
try:
subprocess.run(ffmpeg_command, check=True)
print(f"Videos concatenated successfully into {output_file}")
except subprocess.CalledProcessError as e:
print(f"Error during ffmpeg execution: {e}")
sys.exit(1)
finally:
if os.path.exists(input_file):
os.remove(input_file)
def main():
parser = ArgumentParser(description="Concatenate videos using ffmpeg.")
parser.add_argument("videos", nargs="+",
help="List of videos to concatenate")
parser.add_argument("-o", "--output", required=True,
help="Output video file name")
args = parser.parse_args()
for video in args.videos:
if not os.path.exists(video):
print(f"File not found: {video}")
sys.exit(1)
concat_videos(args.videos, args.output)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment