ffmpy concatenate multiple files with a file list

2019-08-28 04:03发布

问题:

I'm currently trying to merge multiple video files with a python script using ffmpeg and ffmpy. The names of the files are being written into a file list, as suggested by the ffmpeg concatenate wiki.

In my example I'm only using two files, but in practice, there will be several hundert files, that's why I'm choosing the file list approach.

My current code looks like this:

import os
import ffmpy


base_dir = "/path/to/the/files"

# where to seek the files
file_list = open("video_list.txt", "x")

# scan for the video files
for root, dirs, files in os.walk(base_dir):
    for video_file in files:
        if video_file.endswith(".avi"):
            file_list.write("file './%s'\n" % video_file)

# merge the video files
ff = ffmpy.FFmpeg(
    global_options={"-f",
                    "concat ",
                    "-safe",
                    "0"},
    inputs={file_list: None},
    outputs={"-c",
             "copy",
             "output.avi"},
)
ff.run()

So the code I want to run with ffmpy is

ffmpeg -f concat -safe 0 -i video_list.txt -c copy output.avi

But unfortunately my script isn't working and the resulting error is

Traceback (most recent call last):
  File "concat.py", line 20, in <module>
    "output.avi", }
  File "/usr/lib/python3.7/site-packages/ffmpy.py", line 54, in __init__
    self._cmd += _merge_args_opts(outputs)
  File "/usr/lib/python3.7/site-packages/ffmpy.py", line 187, in _merge_args_opts
    for arg, opt in args_opts_dict.items():
AttributeError: 'set' object has no attribute 'items'

Any hints why the command isn't working the way it should? Am I missing something regarding the command formatting for ffmpy?

Thank you.

回答1:

As a working workaround, I was able to call ffmpeg with a subprocess routine, since ffmpy still gave me headache. If somebody else has this problem, here is the code I'm using

import os
import subprocess
import time


base_dir = "/path/to/the/files"
video_files = "video_list.txt"
output_file = "output.avi"

# where to seek the files
file_list = open(video_files, "w")

# remove prior output
try:
    os.remove(output_file)
except OSError:
    pass

# scan for the video files
start = time.time()
for root, dirs, files in os.walk(base_dir):
    for video in files:
        if video.endswith(".avi"):
            file_list.write("file './%s'\n" % video)
file_list.close()

# merge the video files
cmd = ["ffmpeg",
       "-f",
       "concat",
       "-safe",
       "0",
       "-loglevel",
       "quiet",
       "-i",
       "%s" % video_files,
       "-c",
       "copy",
       "%s" % output_file
       ]

p = subprocess.Popen(cmd, stdin=subprocess.PIPE)

fout = p.stdin
fout.close()
p.wait()

print(p.returncode)
if p.returncode != 0:
    raise subprocess.CalledProcessError(p.returncode, cmd)

end = time.time()
print("Merging the files took", end - start, "seconds.")