0

I have a directory with 1000+ video files. I'd like to concatenate them two-by-two.

An alphabetical ordering of the files give the desired pairs, e.g., the input files

 filename_1.mp4
 filename_2.mp4
 filename_3.mp4
 filename_4.mp4
 ...

should result in output files

 filename_1-2.mp4
 filename_3-4.mp4
 ...

They input files all have the same dimensions and formats.

How can I write a batch script invoking ffmpeg to achieve this?

Carl
  • 937
  • 10
  • 21
dellyice
  • 3
  • 1
  • Welcome to the site! I took the liberty to re-write the question in a more compact and comprehensible form. Just a question: with those file names, wouldn't an alphabetical sort give you wrong pairs unless you left-pad the numbers by `0`'s, e.g. `filename_0001.mp4` etc.? – Carl Feb 16 '21 at 22:12
  • Based upon the fact that you're intending to do this with `.mp4` files, I'd strongly advise that you first read [this question](https://stackoverflow.com/q/7567713/6738015), and its answers. – Compo Feb 16 '21 at 22:14
  • Examples of code you've tried are always good https://www.youtube.com/watch?v=BV3QgDq2TGw – Magoo Feb 17 '21 at 05:43
  • 1
    @Carl Your edit adds some confusion. "merge videos two-by-two" made me assume the question is about a [2x2 grid](https://stackoverflow.com/a/33764934/). A better title would be something like "batch concatenate pairs of videos". – llogan Feb 18 '21 at 20:50
  • @llogan absolutely agree, title edited to your suggestion. – Carl Feb 18 '21 at 20:54

1 Answers1

3

One possible solution is to loop through all of the files, and perform a simple binary switch either capturing the filename, or operating on the previously captured filename and the current file:

@echo off

setlocal enabledelayedexpansion enableextensions
set _last=

for %%a in (*.mp4) do (
    if "!_last!" == "" (
        set _last=%%a
    ) else (
        echo merging "!_last!" and "%%a" to "%%a_combined.mp4"
        echo file '!_last!'>simple_list.txt
        echo file '%%a'>>simple_list.txt
        rem Obviously, change this depending on how you want to invoke ffmpeg
        ffmpeg -f concat -safe 0 -i simple_list.txt -c copy "%%a_combined.mp4"
        del simple_list.txt

        set _last=
    )
)

if not "!_last!" == "" (
    echo !_last! was unprocessed!
)

While this works, I'd highly recommend you consider approaching this task with something like Python. For instance, if you wanted to process ten files in a batch, it'd absolutely be possible in a batch file, but almost trivial in a Python script. Or, if you want to combine, say "10 minutes" of videos to one file, it's possible in Python, but nearly impossible in a batch file.

Anon Coward
  • 9,784
  • 3
  • 26
  • 37