Idealisan

Windows上使用powershell脚本快速合并视频

一个powershell脚本,调用ffmpeg命令,把当前文件夹中的所有mp4视频按照文件名字符串排序通过复制流的方式拼接起来,从而快速合并视频文件

# 1. 获取当前目录下所有的 mp4 文件,并按文件名排序
$files = Get-ChildItem -Filter *.mp4 | Sort-Object Name

if ($files.Count -lt 2) {
    Write-Host "未发现足够的 mp4 文件进行合并(至少需要2个文件)。" -ForegroundColor Yellow
    return
}

# 2. 构造输出文件名:第一个文件名 + 最后一个文件名
# 使用 .BaseName 获取不带后缀的文件名
$firstName = $files[0].BaseName
$lastName = $files[-1].BaseName
$outputFile = "${firstName}_to_${lastName}.mp4"
$tempList = "file_list_temp.txt"

# 排除可能已经存在的同名输出文件,防止循环包含
$files = $files | Where-Object { $_.Name -ne $outputFile }

Write-Host "待合并文件范围: " -ForegroundColor Cyan
Write-Host "从: $($files[0].Name)"
Write-Host "到: $($files[-1].Name)"
Write-Host "输出文件名将为: $outputFile" -ForegroundColor Green

# 3. 生成 FFmpeg 要求的列表文件
# 处理文件名中的单引号以防 FFmpeg 报错
$fileContent = $files | ForEach-Object { "file '$($_.Name -replace "'", "''")'" }
[System.IO.File]::WriteAllLines("$pwd\$tempList", $fileContent)

# 4. 调用 FFmpeg 进行合并
# -n: 如果输出文件已存在,直接覆盖(或可改为 -y)
Write-Host "`n正在快速合并..." -ForegroundColor Green
ffmpeg -f concat -safe 0 -i $tempList -c copy "$outputFile"

# 5. 清理临时文件
if (Test-Path $tempList) {
    Remove-Item $tempList
}

if (Test-Path $outputFile) {
    Write-Host "`n合并成功!" -ForegroundColor Green
    Write-Host "文件保存在: $outputFile"
}
分类

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注