Skip to content

Instantly share code, notes, and snippets.

@Antisunny
Created May 20, 2024 07:33
Show Gist options
  • Save Antisunny/41e2902cbf07361148e5309c8cdbe4f6 to your computer and use it in GitHub Desktop.
Save Antisunny/41e2902cbf07361148e5309c8cdbe4f6 to your computer and use it in GitHub Desktop.
批量将.ncm转换成.mp3、.flac文件

批量转换NCM文件

基于 magic-akari/ncmc

输入说明

  • 保存目录通过NCM_SAVE_TO环境指定
  • 输入参数支持.ncm文件或者文件夹
    • 文件夹可以嵌套多层的,程序会一层一层查找.ncm文件
NCM_SAVE_TO=~/Music ./convert.sh .

输出说明

例如歌曲Charlie Puth - Lipstick.ncm文件,会得到

  • Charlie Puth - Lipstick.flac
  • Charlie Puth - Lipstick.data/
    • Charlie Puth - Lipstick.comment
    • Charlie Puth - Lipstick.jpeg
    • Charlie Puth - Lipstick.key
    • Charlie Puth - Lipstick.ncm
    • Charlie Puth - Lipstick.json

这样目录结构的数据们。

#!/usr/local/bin/bash
# based on https://github.com/magic-akari/ncmc
declare -a musicexts
musicexts=(mp3 flac)
declare -a fileexts
fileexts=(comment key json jpeg jpg)
function process_single_ncm_file {
filepath=$1
filename=`basename "$filepath"`
save_to_dir=$2
if [ ! -e "$save_to_dir" ]; then
mkdir -p "$save_to_dir"
fi
# 将源文件.ncm文件拷贝到save_to_dir
mv "$filepath" "$save_to_dir"
#
filedirname=${filename/.ncm/.data}
if [ -e "$save_to_dir/$filedirname" ]; then
printf "dir '$filedirname' exists in '$save_to_dir'!\n"
return 2
fi
mkdir "$save_to_dir/$filedirname"
ncmc --dump "$save_to_dir/$filename" &> /dev/null
# 这样生成的.mp3、.flac文件是没有metadata的
filenamebase=${filename/.ncm/}
for ext in ${fileexts[@]}; do
if [ ! -e "$save_to_dir/$filenamebase.$ext" ]; then
continue
fi
mv "$save_to_dir/$filenamebase.$ext" "$save_to_dir/$filedirname"
done
for ext in ${musicexts[@]}; do
if [ -e "$save_to_dir/$filenamebase.$ext" ]; then
rm "$save_to_dir/$filenamebase.$ext"
fi
done
ncmc "$save_to_dir/$filename" &> /dev/null
# 生成的.mp3、.flac文件有metadata
mv "$save_to_dir/$filename" "$save_to_dir/$filedirname"
}
function process_single_dir {
dirpath=$1
save_to_dir=$2
for entry in "$dirpath"/*; do
if [ -f "$entry" ] && [[ "$entry" == *".ncm" ]]; then
echo \[processing ncm file "'"$entry"'"\]
process_single_ncm_file "$entry" "$save_to_dir"
continue
fi
if [ -d "$entry" ]; then
echo \[processing dir "'"$entry"'"\]
process_single_dir "$entry" "$save_to_dir"
continue
fi
done
}
save_to=""
if [[ "x$NCM_SAVE_TO" == "x" ]]; then
save_to="." #当前目录
else
save_to="$NCM_SAVE_TO"
fi
for entry in "$@"; do
if [ -d "$entry" ]; then
echo \[processing dir "'"${entry%*/}"'"\]
process_single_dir ${entry%*/} "$save_to"
continue
fi
# 直接给的ncm文件
if [ -f "$entry" ] && [[ "$entry" != *".ncm" ]]; then
printf "'$filename' is not a .ncm file!\n"
continue
fi
echo \[processing "'$entry'"\]
process_single_ncm_file "$entry" .
status="$?"
if [[ "$status" == "2" ]]; then
continue
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment