本文目录导读:

我来介绍几种批量转换视频格式的方法,从简单到高级:
使用 FFmpeg + Shell 脚本(推荐)
Windows (PowerShell)
# 批量转换mp4为avi
Get-ChildItem *.mp4 | ForEach-Object {
$output = $_.BaseName + ".avi"
ffmpeg -i $_.Name -c:v libx264 -c:a aac $output
Write-Host "转换完成: $($_.Name) -> $output"
}
Linux/Mac (Bash)
#!/bin/bash
# 批量转换mp4为mkv
for file in *.mp4; do
filename="${file%.*}"
ffmpeg -i "$file" -c:v libx264 -c:a aac "${filename}.mkv"
echo "转换完成: $file -> ${filename}.mkv"
done
进阶脚本(带参数控制)
#!/usr/bin/env python3
import os
import subprocess
from pathlib import Path
def batch_convert(input_dir, output_dir, input_ext, output_ext):
"""批量转换视频格式"""
input_ext = input_ext.lower()
output_ext = output_ext.lower()
# 创建输出目录
Path(output_dir).mkdir(parents=True, exist_ok=True)
for file in Path(input_dir).glob(f"*{input_ext}"):
output_file = Path(output_dir) / f"{file.stem}{output_ext}"
# 构建ffmpeg命令
cmd = [
"ffmpeg", "-i", str(file),
"-c:v", "libx264", # 视频编码
"-c:a", "aac", # 音频编码
"-preset", "medium", # 转换速度/质量平衡
"-crf", "23", # 质量参数(18-28,越小质量越好)
str(output_file)
]
print(f"正在转换: {file.name} -> {output_file.name}")
subprocess.run(cmd, check=True)
print("全部转换完成!")
# 使用示例
batch_convert("./input", "./output", ".mp4", ".mkv")
批量转换常用格式对照
# MP4 转 AVI ffmpeg -i input.mp4 -c:v libx264 -c:a mp3 output.avi # MKV 转 MP4 ffmpeg -i input.mkv -c:v copy -c:a copy output.mp4 # 直接复制编码 # MOV 转 MP4(H.265编码) ffmpeg -i input.mov -c:v libx265 -c:a aac output.mp4 # WebM 转 MP4 ffmpeg -i input.webm -c:v libx264 -c:a aac output.mp4
图形界面工具(免脚本)
如果不想写脚本,可以使用:
- HandBrake CLI:有命令行版本,支持批量
- ffmpeg-batch:专门批量转换的小工具
- Any Video Converter:GUI工具但支持批量
带进度显示的脚本
#!/bin/bash
# 批量转换并显示进度
TOTAL=$(ls -1 *.mp4 2>/dev/null | wc -l)
COUNT=0
for file in *.mp4; do
if [ -f "$file" ]; then
COUNT=$((COUNT + 1))
echo "[$COUNT/$TOTAL] 正在转换: $file"
ffmpeg -i "$file" -c:v libx264 -c:a aac \
-stats \
"${file%.*}.mkv" 2>&1 | grep -oP '\d+\.\d+%' | tail -1
echo "完成: $file"
fi
done
使用建议
- 先安装 FFmpeg:https://ffmpeg.org/download.html
- 测试单个文件:先用一条命令测试参数
- 添加错误处理:生产环境建议添加
try-catch或检查返回码 - 考虑 CPU 负载:可以添加
-threads N限制线程数
需要针对特定格式或场景的转换脚本吗?