xiandie/ogg_converter/convert_ogg.sh

97 lines
2.3 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# convert_ogg.sh - Convert WAV and MP3 files to OGG format
# Usage: ./convert_ogg.sh [quality] [directory]
# Quality range: 0-10 (default: 7), Directory (default: current)
set -euo pipefail # 严格错误处理
# 默认参数
QUALITY=${1:-7}
TARGET_DIR=${2:-.}
EXTENSIONS=("mp3" "wav")
# 验证质量参数
if ! [[ "$QUALITY" =~ ^[0-9]|10$ ]]; then
echo "错误:质量参数必须在 0-10 之间" >&2
exit 1
fi
# 验证目录存在
if [[ ! -d "$TARGET_DIR" ]]; then
echo "错误:目录 '$TARGET_DIR' 不存在" >&2
exit 1
fi
# 检查 ffmpeg 是否安装
if ! command -v ffmpeg &> /dev/null; then
echo "错误:未找到 ffmpeg请先安装" >&2
exit 1
fi
# 转换函数
convert_to_ogg() {
local input_file="$1"
local output_file="${input_file%.*}.ogg"
# 检查输出文件是否已存在
if [[ -f "$output_file" ]]; then
read -p "文件 '$output_file' 已存在,是否覆盖?(y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "跳过:$input_file"
return 0
fi
fi
echo "转换中:$input_file -> $output_file"
if ffmpeg -i "$input_file" -c:a libvorbis -qscale:a "$QUALITY" "$output_file" -y &>/dev/null; then
echo "✓ 完成:$output_file"
return 0
else
echo "✗ 失败:$input_file" >&2
return 1
fi
}
# 主逻辑
cd "$TARGET_DIR"
total_files=0
converted_files=0
failed_files=0
# 统计文件总数
for ext in "${EXTENSIONS[@]}"; do
count=$(find . -maxdepth 1 -name "*.$ext" -type f | wc -l)
total_files=$((total_files + count))
done
if [[ $total_files -eq 0 ]]; then
echo "在 '$TARGET_DIR' 中未找到 MP3 或 WAV 文件"
exit 0
fi
echo "找到 $total_files 个文件,质量设置:$QUALITY"
echo "开始转换..."
echo
# 转换文件
for ext in "${EXTENSIONS[@]}"; do
while IFS= read -r -d '' file; do
if convert_to_ogg "$file"; then
((converted_files++))
else
((failed_files++))
fi
done < <(find . -maxdepth 1 -name "*.$ext" -type f -print0)
done
# 显示结果统计
echo
echo "转换完成!"
echo "成功:$converted_files 个文件"
if [[ $failed_files -gt 0 ]]; then
echo "失败:$failed_files 个文件"
exit 1
fi