Sunday, December 7, 2008

FLAC to MP3

Converting a FLAC (or whatever else) to mp3 on Linux is so easy that I felt like telling the whole world about it (I know.. I know.. you know already!).

My girlfrienf just happend to have this old CD she ripped like ages ago to files in *.flac format. She wanted to use them on her portable player but.. well it just didn't support it. I decided to quickly help her and googled a bit. What I found out was that people try to make money on this particular problem. It's amazing!! Poor windows users need to buy a converter software for about $30 to easily accomplish this task. Since the free tools are already there (lame and flac) I just wrote this simple bash script to get the task done. Try it yourserlf!

If you are a "poor" windows user, then I guess (.. well I never tried it) you may run the script with Cygwin. Better solution for you would be to install yourself Ubuntu or any other Linux distribution.



#!/bin/sh
#
# Convert all flac files in the current dir to mp3 (lame) format.
#

BITRATE=320
SAMPLE=48

usage() {
echo "USAGE: `basename $0` [bitrate] [sample]"
echo "params:"
echo " bitrate - a number in kbps (e.g. 128 or 320)"
echo " sample - sampling frequency in kHz (e.g. 44 or 48)"
}

if [ $# -gt 2 ] || [ "$1" == "--help" ]; then
usage;
exit 1;
elif [ $# -eq 1 ]; then
BITRATE=$1
elif [ $# -eq 2 ]; then
BITRATE=$1
SAMPLE=$2
fi

usage;

for file in *.flac; do
#
# Song information
#
TITLE="`metaflac --show-tag=TITLE "$file" | awk -F = '{ printf($2) }'`"
ALBUM="`metaflac --show-tag=ALBUM "$file" | awk -F = '{ printf($2) }'`"
ARTIST="`metaflac --show-tag=ARTIST "$file" | awk -F = '{ printf($2) }'`"
TRACKNUMBER="`metaflac --show-tag=TRACKNUMBER "$file" | awk -F = '{ printf($2) }'`"
GENRE="`metaflac --show-tag=GENRE "$file" | awk -F = '{ printf($2) }'`"
COMMENT="`metaflac --show-tag=COMMENT "$file" | awk -F = '{ printf($2) }'`"
DATE="`metaflac --show-tag=DATE "$file" | awk -F = '{ printf($2) }'`"

#
# Print some info
#
echo "Converting the song: $ARTIST - $TITLE ($file)";

#
# Convert the song
#
$(flac -cd "$file" | lame -b $BITRATE --resample $SAMPLE \
--add-id3v2 --tt "$TITLE" --ta "$ARTIST" --tn "$TRACKNUMBER" \
--tg "$GENRE" --ty "$DATE" --tl "$ALBUM" \
-h - "${file%.flac}.mp3");
done

exit 0;

No comments: