MP3 to ogg, preserving tags
April 20th, 2008
I personally don’t like all those insane 320kbit bitrates, I’m perfectly fine with listening to 80kbit ogg(which sounds like 128kbit mp3 occupying less space at the same time). As it’s impossible to convert from inside iTunes(oh, Foobar, where art thou?) I had to resort to command line tools. The tools we’ll need are
- LAME - mp3 encoder
- eggenc - ogg encoder(you’ll need to build libogg, libvorbis, vorbis-tools but it builds out-of-box)
- id3tool - mp3 tag viewer(and editor) - also builds successfully
- Grep and sed - text manipulators, powerful standard tools
Now the bash script which will convert all the supplied mp3 files to ogg(mp32ogg):
for file in "$@"
do
if test ! -f "$(basename "$file" .mp3).ogg"
then
lame --decode "$file"
ARTIST=`id3tool "$file" | grep Artist | sed s/Artist:// | sed 's/[^A-Za-z0-9]*//'`
ALBUM=`id3tool "$file" | grep Album | sed s/Album:// | sed 's/[^A-Za-z0-9]*//'`
TRACK=`id3tool "$file" | grep Track | sed s/Track:// | sed 's/[^A-Za-z0-9]*//'`
YEAR=`id3tool "$file" | grep Year | sed s/Year:// | sed 's/[^A-Za-z0-9]*//'`
GENRE=`id3tool "$file" | grep Genre | sed s/Genre:// | sed -e 's/[^A-Za-z0-9]*//' -e 's/(.*)$//'`
oggenc -a "$ARTIST" -G "$GENRE" -d "$YEAR" -N "$TRACK" -l "$ALBUM" -b 80 "$file.wav" -o "$(basename "$file" .mp3).ogg"
rm "$file.wav"
fi
done
In case you wonder why it uses such strange long lines, the process of getting the artist for example can be described as follows:
- id3tool “$file” - get tags
- grep Artist - get line containing word Artist
- sed s/Artist:// - remove the preceding string “Artist:” from the line
- sed ’s/[^A-Za-z0-9]*// - remove the unnecessary spaces/tabs/etc… before the artist name itself(the actual meaning is remove all characters before encountering alphanumerical - A-Z or a-z or 0-9)
Btw, basename “$file” .mp3 is just a neat way to strip mp3 extension preserving the filename itself.
The syntax is straightforward - you could use built-in wildcards - e.g. mp32ogg T*.mp3 will convert all mp3 files starting with T.



