python - 根据 Python 中文件名中的数字按顺序组合 mp4 文件

标签 python ffmpeg operating-system subprocess

我尝试合并很多 mp4目录中的文件 test合二为一output.mp4使用 ffmpeg在 Python 中。

path = '/Users/x/Documents/test'

import os

for filename in os.listdir(path):
    if filename.endswith(".mp4"):
        print(filename)

输出:
4. 04-unix,minix,Linux.mp4
6. 05-Linux.mp4
7. 06-ls.mp4
5. 04-unix.mp4
9. 08-command.mp4
1. 01-intro.mp4
3. 03-os.mp4
8. 07-minux.mp4
2. 02-os.mp4
10. 09-help.mp4

我从这里的引用资料中尝试了以下解决方案:ffmpy concatenate multiple files with a file list
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.")

我已将它们合并并得到 output.mp4但是文件没有按第一个按点分割的数字( 1, 2, 3, ... )按顺序合并:我可以通过 filename.split(".")[0] 得到:
1. 01-intro.mp4
2. 02-os.mp4
3. 03-os.mp4
4. 04-unix,minix,Linux.mp4
5. 04-unix.mp4
6. 05-Linux.mp4
7. 06-ls.mp4
8. 07-minux.mp4
9. 08-command.mp4
10. 09-help.mp4

如何在 Python 中正确简洁地合并它们?谢谢。

最佳答案

此解决方案有效:

from moviepy.editor import *
import os
from natsort import natsorted

L =[]

for root, dirs, files in os.walk("/path/to/the/files"):

    #files.sort()
    files = natsorted(files)
    for file in files:
        if os.path.splitext(file)[1] == '.mp4':
            filePath = os.path.join(root, file)
            video = VideoFileClip(filePath)
            L.append(video)

final_clip = concatenate_videoclips(L)
final_clip.to_videofile("output.mp4", fps=24, remove_temp=False)

关于python - 根据 Python 中文件名中的数字按顺序组合 mp4 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56920546/

相关文章:

python - shutil.rmtree 在 Windows 上失败并显示 'Access is denied'

python - (Python) 启动外部应用程序并等待它结束

ios - Xcode 9 中的 FFMpeg 错误 - 类型 'AVMediaType' 的定义与同名的 typedef 冲突

audio - 使用ffmpeg提取视频文件的英语音频

linux-kernel - Linux 内核 ARM 转换表库(TTB0 和 TTB1)

python - Glob 不打印结果

python - 我将 djang1.3.1 更新为 djang1.4 ,错误 : MOD_PYTHON ERROR

python - 您可以使用 ffmpeg 流从文件实时插入文本吗?

assembly - 操作系统如何阻止程序访问内存?

python - spaCy 共指解析 - 命名实体识别(NER)以返回唯一实体 ID?