ffmpeg 批量从视频文件中提取音频
2025-01-22 08:19:30    500 字   
This post is also available in English and alternative languages.

使用 ffmpeg 批量从 MP4、MKV 视频文件中提取音频(MP3)


1. 安装 ffmpeg

1
brew install ffmpeg

2. 从 Video 中提取音频

脚本会递归扫描输入目录(及子目录)中的 MP4 和 MKV 视频文件。

新建一个.sh扩展名的脚本,粘贴以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/bin/bash

# 检查输入参数
if [ $# -ne 2 ]; then
echo "Usage: $0 input_dir output_dir"
echo "This script recursively extracts audio tracks from video files in the input directory and saves them as MP3 files in the output directory."
echo "Arguments:"
echo " input_dir: The directory containing the input video files (including subdirectories)."
echo " output_dir: The directory where the extracted MP3 files will be saved."
echo "Notes:"
echo " - The script supports processing both '.mp4' and '.mkv' video files."
echo " - Audio tracks are extracted in MP3 format."
echo " - For '.mp4' files, audio is extracted without any additional options."
echo " - For '.mkv' files, audio is extracted with the '64k' audio bitrate and saved as MP3 files."
exit 1
fi

input_dir="$1"
output_dir="$2"

# 检查输入目录是否存在且不为空
if [ ! -d "$input_dir" ] || [ -z "$(ls -A "$input_dir")" ]; then
echo "Input directory does not exist or is empty."
exit 1
fi

# 如果输出目录不存在,则创建输出目录
if [ ! -d "$output_dir" ]; then
mkdir -p "$output_dir"
fi

# 使用find命令获取所有视频文件列表并保存到数组中
video_files=()
while IFS= read -r -d $'\0'; do
video_files+=("$REPLY")
done < <(find "$input_dir" -type f \( -name "*.mp4" -o -name "*.mkv" \) -print0)

# 用for循环遍历视频文件列表并处理视频转换
for file in "${video_files[@]}"; do
# 提取文件名和扩展名
filename=$(basename "$file")
extension="${filename##*.}"

# 根据视频格式选择不同的 ffmpeg 命令进行处理
if [ "$extension" == "mp4" ]; then
ffmpeg -i "$file" -f mp3 -vn "$output_dir/${filename%.*}.mp3"
elif [ "$extension" == "mkv" ]; then
ffmpeg -i "$file" -map 0:1 -b:a 64k -f mp3 "$output_dir/${filename%.*}.mp3"
fi
done

echo "Extract complete."

3. 运行脚本

在 Terminal(命令行) 中执行以下代码即可:

1
bash /path/to/your/script.sh inputPath outputPath