Skip to content

Instantly share code, notes, and snippets.

@zgs225
Last active April 26, 2023 07:16
Show Gist options
  • Save zgs225/40eebe08a8f0c05f89e160f684083eda to your computer and use it in GitHub Desktop.
Save zgs225/40eebe08a8f0c05f89e160f684083eda to your computer and use it in GitHub Desktop.
将 mp3 文件中的繁体中文信息转换成简体中文信息
#!/bin/bash
# 将 mp3 文件中的繁体字转换为简体字
# 依赖:opencc mid3v2
# 用法:hant2hans.sh [-d dir] [-f file]
set -e
function get_by_id() {
mid3v2 -l "$1" | grep "$2" | cut -d= -f2 | sed 's/^[ \t]*//'
}
function convert_single_file() {
local file="$1"
if [ ! -f "$file" ]; then
echo "Error: $file is not a file"
exit 1
fi
local title="$(get_by_id "$file" TIT2)"
local artist="$(get_by_id "$file" TPE1)"
local album="$(get_by_id "$file" TALB)"
local title_s="$(echo "$title" | opencc -c t2s.json)"
local artist_s="$(echo "$artist" | opencc -c t2s.json)"
local album_s="$(echo "$album" | opencc -c t2s.json)"
echo "mid3v2 -t \"$title_s\" -a \"$artist_s\" -A \"$album_s\" \"$file\""
mid3v2 -t "$title_s" -a "$artist_s" -A "$album_s" "$file"
}
function convert_dir() {
local dir="$1"
if [ ! -d "$dir" ]; then
echo "Error: $dir is not a directory"
exit 1
fi
local files="$(find "$dir" -type f -name "*.mp3")"
echo "$files" | while read file; do
convert_single_file "$file"
done
}
function usage() {
echo "Usage: $0 [-d dir] [-f file]"
exit 0
}
function check_dependency() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "Error: $1 is not installed"
exit 1
fi
}
check_dependency opencc
check_dependency mid3v2
if [ $# -eq 0 ]; then
usage
exit 0
fi
while getopts "d:f:h" arg; do
case $arg in
d)
convert_dir "$OPTARG"
;;
f)
convert_single_file "$OPTARG"
;;
h)
usage
exit 0
;;
?)
echo "unkonw argument"
exit 1
;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment