使用 FFMPEG 批量修复视频为统一常见参数的脚本

2026-01-23 15:52:36 13 分享链接 开发笔记 ffmpeg python

import os
import subprocess

# 直接在代码中定义参数
# ffmpeg -f concat -safe 0 -i "D:/000/videos3.txt" -vf "fps=60,scale=1080:1920" -c:v h264_nvenc -cq 16 -gpu 0 -preset medium -y "D:/000/00073.mp4"
VIDEO_DIR = "D:/VideoDown/车厘子"  # 视频所在目录
OUTPUT_DIR = "D:/VideoNew/车厘子"  # 输出目录
CONCAT_FILE = "D:/VideoDown/videos.txt"  # 生成的concat文件路径

def main():
    # 创建输出目录
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    # 获取所有MP4文件
    mp4_files = [f for f in os.listdir(VIDEO_DIR) if f.lower().endswith('.mp4')]
    
    if not mp4_files:
        print(f"错误:在目录 '{VIDEO_DIR}' 中未找到MP4文件!")
        return
    
    # 处理每个视频文件
    for i, mp4_file in enumerate(mp4_files, 1):
        input_path = os.path.join(VIDEO_DIR, mp4_file)
        base_name = os.path.splitext(mp4_file)[0]
        output_path = os.path.join(OUTPUT_DIR, f"{base_name}_std.mp4")
        
        print(f"处理文件 {i}/{len(mp4_files)}: {mp4_file}")
        
        # 构建FFmpeg命令
        ffmpeg_cmd = [
            'ffmpeg', '-i', input_path,
            '-s', '1080:1920',       # 强制设置分辨率为1080宽×1920高(竖屏)
            '-sws_flags', 'lanczos', # 可选:使用高质量的兰佐斯插值缩放(提升画质)
            '-c:v', 'h264_nvenc',    # 使用NVIDIA硬件编码
            '-cq', '16',           
            '-gpu', '0',           
            '-r', '60',              # 设置帧率为60fps
            # '-g', '120',           # 设置GOP大小为120
            # '-keyint_min', '120',  # 最小I帧间隔为120
            # '-sc_threshold', '0',  # 关闭场景检测
            # '-b:v', '12M',         # 视频比特率
            # '-maxrate', '15M',     # 最大比特率
            '-bufsize', '20M',       # 缓冲区大小
            '-pix_fmt', 'yuv420p',   # 像素格式
            '-video_track_timescale', '60',  # 统一时间基
            '-an',                   # 移除音频
            '-y',                    # 覆盖已存在文件
            output_path
        ]
        
        try:
            # 执行FFmpeg命令
            subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            print(f"成功:{mp4_file} 已处理")
        except subprocess.CalledProcessError as e:
            print(f"错误:处理 {mp4_file} 时出错")
            print(f"错误详情: {e.stderr.decode('utf-8')}")
            continue  # 继续处理下一个文件
    
    # 创建concat文件
    print("\n创建concat文件...")
    
    with open(CONCAT_FILE, 'w', encoding='utf-8') as f:
            # 获取所有标准化后的视频文件
            std_files = sorted([f for f in os.listdir(OUTPUT_DIR) if f.endswith('_std.mp4')])
            
            if not std_files:
                print("错误:没有找到标准化后的视频文件!")
                return
            
            # 写入concat文件(提前处理路径中的反斜杠)
            for std_file in std_files:
                file_path = os.path.join(OUTPUT_DIR, std_file)
                # 先替换反斜杠,再放入f-string
                formatted_path = file_path.replace('\\', '/')
                f.write(f"file '{formatted_path}'\n")
        
    print(f"完成!concat文件已生成: {CONCAT_FILE}")

if __name__ == "__main__":
    main()

使用 FFMPEG 批量修复视频为统一常见参数的脚本