How to use Python's ffmpy3 package to batch merge TS files into a single MP4 file.

Before reading, you need to know:

  • ffmpy3 is a Python wrapper for FFmpeg
  • ffmpy3 complies FFmpeg command line based on provided parameters and options

Using ffmpy3

Installing ffmpy3 Package

Install using pip:

1
pip install ffmpy3

Simple ffmpy3 Example

1
2
3
4
5
import ffmpy3
ff = ffmpy3.FFmpeg(
inputs={'input_file': 'parameter1'},
outputs={'output_file': 'parameter2'}
)

The final result is equivalent to entering in terminal:

1
FFmpeg parameter1 -i input_file parameter2 output_file

Batch Merging TS Files

Directory Structure

1
2
3
4
5
6
7
8
├───folder
│ python_file.py
│ file.txt
│ fileA.ts
│ fileB.ts
│ fileC.ts
│ fileD.ts
...

file.txt

Write the TS filenames in file.txt:

1
2
3
4
file 'fileA.ts'
file 'fileB.ts'
file 'fileC.ts'
file 'fileD.ts'

Note:

  1. Use single quotes, not double quotes - the latter will cause errors!
  2. Use relative paths within the quotes

Python File

Use this code to batch merge TS files:

1
2
3
4
5
ff = ffmpy3.FFmpeg(
inputs={f'file.txt': '-f concat'},
outputs={f'filename.mp4': '-c copy'}
)
ff.run()

The above code is equivalent to entering in terminal:

1
FFmpeg -f concat -i file.txt -c copy filename.mp4