import os
import glob
from natsort import natsorted

# 当前文件夹下的所有 mp4 路径
L = []
dir_path = r'E:\home\up'
output_dir = r'E:\home\up\1'
for root, dirs, files in os.walk(dir_path):
    files = natsorted(files)
    for file in files:
        if os.path.splitext(file)[1] == '.mp4':
            file_path = os.path.join(root, file)
            L.append(file_path)

# 生成 ffmpeg 命令
commands = []
for l in L:
    ts_file = os.path.join(
        os.path.dirname(l), os.path.splitext(os.path.basename(l))[0] + '.ts')
    commands.append(
        f'ffmpeg -i \'{l}\' -vcodec copy -acodec copy -bsf:v h264_mp4toannexb \'{ts_file}\'')

concat_command = (
    f'ffmpeg -i \'concat:{\'|'.join([os.path.join(os.path.dirname(l), os.path.splitext(os.path.basename(l))[0] + '.ts') for l in L])}\' '
    '-acodec copy -vcodec copy -bsf:a aac_adtstoasc '
    f'\'{os.path.join(output_dir, os.path.splitext(os.path.basename(L[0]).replace('00', '-', 1))[0][1:].upper()) + '.mp4}\'')

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

os.system(concat_command)

# 删除 ts 文件
for ts_file in glob.glob(os.path.join(dir_path, '*.ts')):
    os.remove(ts_file)

该脚本首先使用 os.walk() 函数遍历指定的目录 dir_path,找到所有以 .mp4 结尾的文件,并将它们的路径存储在列表 L 中。

然后,脚本使用 ffmpeg 命令将每个 mp4 文件转换为 ts 文件,并存储在 commands 列表中。

最后,脚本使用 ffmpeg 命令将所有 ts 文件合并成一个新的 mp4 文件,并对输出文件进行重命名,删除文件名中第一个英文字母前的所有字符。

注意:

  • 该脚本需要安装 ffmpegnatsort 库。
  • 脚本中的 dir_pathoutput_dir 需要根据实际情况进行修改。
  • 脚本中的 replace('00', '-', 1) 用于将文件名中的 00 替换成 -,以便对输出文件进行排序。
  • 脚本中的 [1:].upper() 用于删除文件名中第一个字符并将其余字符转换为大写。
Python 脚本:批量合并 MP4 文件并重命名输出文件

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

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