如何通过命令行或批处理脚本与ffmpeg转换整个目录/文件夹?


当前回答

一行bash脚本很容易完成——替换*。Avi与您的文件类型:

for i in *.avi; do ffmpeg -i "$i" -qscale 0 "$(basename "$i" .avi)".mov  ; done

其他回答

使用多核,这是最快的方法,(使用并行):

parallel "ffmpeg -i {1} {1.}.mp4" ::: *.avi 

小PHP脚本来做它:

#!/usr/bin/env php
<?php
declare(strict_types = 1);
if ($argc !== 2) {
    fprintf ( STDERR, "usage: %s dir\n", $argv [0] );
    die ( 1 );
}
$dir = rtrim ( $argv [1], DIRECTORY_SEPARATOR );
if (! is_readable ( $dir )) {
    fprintf ( STDERR, "supplied path is not readable! (try running as an administrator?)" );
    die(1);
}
if (! is_dir ( $dir )) {
    fprintf ( STDERR, "supplied path is not a directory!" );
    die(1);
}
$files = glob ( $dir . DIRECTORY_SEPARATOR . '*.avi' );
foreach ( $files as $file ) {
    system ( "ffmpeg -i " . escapeshellarg ( $file ) . ' ' . escapeshellarg ( $file . '.mp4' ) );
}

要转换子目录,请使用例如。

find . -exec ffmpeg -i {} {}.mp3 \;

下面的脚本在Windows上的Bash中工作得很好(所以它在Linux和Mac上也应该工作得很好)。它解决了我在其他解决方案中遇到的一些问题:

处理子文件夹中的文件 用目标扩展替换源扩展,而不仅仅是附加它 适用于名称中有多个空格和多个点的文件 (详见这个答案。) 可以运行时,目标文件存在,提示之前覆盖

ffmpeg-batch-convert.sh:

sourceExtension=$1 # e.g. "mp3"
targetExtension=$2 # e.g. "wav"
IFS=$'\n'; set -f
for sourceFile in $(find . -iname "*.$sourceExtension")
do
    targetFile="${sourceFile%.*}.$targetExtension"
    ffmpeg -i "$sourceFile" "$targetFile"
done
unset IFS; set +f

示例调用:

$ sh ffmpeg-batch-convert.sh mp3

作为奖励,如果你想删除源文件,你可以像这样修改脚本:

sourceExtension=$1 # e.g. "mp3"
targetExtension=$2 # e.g. "wav"
deleteSourceFile=$3 # "delete" or omitted
IFS=$'\n'; set -f
for sourceFile in $(find . -iname "*.$sourceExtension")
do
    targetFile="${sourceFile%.*}.$targetExtension"
    ffmpeg -i "$sourceFile" "$targetFile"
    if [ "$deleteSourceFile" == "delete" ]; then
        if [ -f "$targetFile" ]; then
            rm "$sourceFile"
        fi
    fi
done
unset IFS; set +f

示例调用:

$ sh ffmpeg-batch-convert.sh mp3

在Windows上:

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"