Super conversion script

I’ve written a script to convert .flac files to .mp3 and retain a useful directory structure. This is mad-handy for my w800i phone.


source_path="${1%/}/";
dest_base="${2%/}/";
bit_rate=$3

if [ ! -r "$source_path" ]; then
echo "Source path not found."
exit 2
fi

if [ ! -r "$dest_base" ]; then
echo "Destination base path not found"
exit 2
fi

if [ ! $bit_rate ]; then
echo "No bit rate specified, defaulting to 128kbps"
bit_rate=128
fi

artist_album=`echo "$source_path" | sed 's:^.*/\([^/]*/[^/]*/[^/]*\)$:\1:'`
dest_path="$dest_base$artist_album"

# Check out source dir
if [ ! "$(ls -A "$source_path"*.flac )" ]; then
echo "No .flac files found in source path."
exit 2;
fi

cd "$source_path"
ls | grep .flac | while read file ;do
# Each flac
title=`metaflac --list --block-type=VORBIS_COMMENT "$file" | grep "TITLE=" | sed "s/comment\[0\]: TITLE=//g" | sed "s/^ *//g"`
artist=`metaflac --list --block-type=VORBIS_COMMENT "$file" | grep "ARTIST=" | sed "s/comment\[1\]: ARTIST=//g" | sed "s/^ *//g"`
tracknumber=`metaflac --list --block-type=VORBIS_COMMENT "$file" | grep "TRACKNUMBER=" | sed "s/comment\[2\]: TRACKNUMBER=//g" | sed "s/^ *//g"`
tracktotal=`metaflac --list --block-type=VORBIS_COMMENT "$file" | grep "TRACKTOTAL=" | sed "s/comment\[3\]: TRACKTOTAL=//g" | sed "s/^ *//g"` album=`metaflac --list --block-type=VORBIS_COMMENT "$file" | grep "ALBUM=" | sed "s/comment\[4\]: ALBUM=//g" | sed "s/^ *//g"`

echo "Converting: $artist - $album [$title]"
flac --silent -d "$file"
wavfile=${file%.flac}.wav
newfile=${file%.flac}.mp3
lame --quiet --tt "$title" --ta "$artist" --tl "$album" --tn $tracknumber --preset "$bit_rate"kbps "$wavfile" "$newfile"
done

rm *.wav
mkdir -p "$dest_path"
mv *.mp3 "$dest_path"

exit 0;

By no means perfect, but it does work. You will need flac and lame installed for this to work. Comments/suggestions welcome!

Leave a Reply