这段代码的功能是批量将当前文件夹下所有的 MP4 文件转换成 TS 文件,然后将所有 TS 文件合并成一个 MP4 文件,并删除中间生成的 TS 文件。

具体实现方式是使用 os 模块遍历当前文件夹下的所有 MP4 文件,然后生成对应的 ffmpeg 命令,并使用 os.system() 函数执行这些命令。其中,生成每个 MP4 文件对应的 ffmpeg 命令时,使用了 natsort 模块对文件名进行自然排序,避免了按照字符串排序时可能会出现的问题。

最后,使用 ffmpeg 命令将所有 TS 文件合并成一个 MP4 文件,并使用 os.system() 函数执行删除所有 TS 文件的命令。

import os
from natsort import natsorted

# 存储当前文件夹下的所有 mp4 文件路径
L = []
for root, dirs, files in os.walk('/home/115/up'):
    files = natsorted(files)
    for file in files:
        # 只处理 mp4 文件
        if os.path.splitext(file)[1] == '.mp4':
            file_path = os.path.join(root, file)
            L.append(file_path)

# 生成 ffmpeg 命令
commands = []
for l in L:
    commands.append(f'ffmpeg -i '{l}' -vcodec copy -acodec copy -bsf:v h264_mp4toannexb '{l.replace('.mp4', '.ts')}'')

concat_command = f'ffmpeg -i 'concat:{'|'.join([i.replace('.mp4', '.ts') for i in L])}' -acodec copy -vcodec copy -bsf:a aac_adtstoasc output.mp4'

rm_command = 'rm *.ts'

# 执行 ffmpeg 命令
for command in commands:
    os.system(command)

os.system(concat_command)
os.system(rm_command)
Python 批量转换 MP4 文件为 TS 并合并成单个 MP4 文件

原文地址: https://www.cveoy.top/t/topic/nzIm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录