Converting ogg/vorbis to mp3

This is a simple bash shell script to convert a folder of .ogg (vorbis) files to mp3 files.  I won’t get into the advantages of one format versus another.  You may have a device that supports only mp3 files.  Therefore, you have a reason to convert .ogg files to .mp3.  There are many scripts out there that will convert ogg to mp3 but with most of them you lose all of your tags in the process.  That can be a real pain.  My script will preserve the tags of my choice and write them to the mp3 file.

The tags that I am concerned about are:

  • Artist
  • Album
  • Title
  • Genre
  • Date (year)
  • Track #

If there are other tags that you care about, then adjust the script as needed.

The shell script depends on the following packages:

  • id3v2
  • vorbis-tools
  • lame

For Ubuntu users:

$ sudo apt-get install id3v2 vorbis-tools lame

For Fedora users:

$ sudo yum install id3v2 vorbis-tools lame

Without further ado, here is the script


#!/bin/bash
# convert *.ogg files to *.mp3 files

function addtag {

ARTIST=`cat $1 | sed -e '/^.*ARTIST/!d' -e 's/^.*ARTIST=//'`
TITLE=`cat $1 | sed -e '/^.*TITLE/!d' -e 's/^.*TITLE=//'`
DATE=`cat $1 | sed -e '/^.*DATE/!d' -e 's/^.*DATE=//'`
GENRE=`cat $1 | sed -e '/^.*GENRE/!d' -e 's/^.*GENRE=//'`
TRACK=`cat $1 | sed -e '/^.*TRACKNUMBER/!d' -e 's/^.*TRACKNUMBER=//'`
ALBUM=`cat $1 | sed -e '/^.*ALBUM/!d' -e 's/^.*ALBUM=//'`

echo "artist: $ARTIST"
echo "title: $TITLE"
echo "album: $ALBUM"
echo "genre: $GENRE"
echo "date: $DATE"
echo "track: $TRACK"

id3v2 --artist "$ARTIST" --album "$ALBUM" \
--song "$TITLE" --genre "$GENRE" \
 --year "$DATE" --track "$TRACK" \
"$(basename "$1" .tag).mp3"

}

for a in *.ogg
do
ogginfo "$a" > "$(basename "$a" .ogg).tag"
oggdec -o - "$a" | lame -h -V 5 --vbr-new - "$(basename "$a" .ogg).mp3"
addtag "$(basename "$a" .ogg).tag"
rm "$(basename "$a" .ogg).tag"
done

I named the script ogg2mp3.sh.  I chose to leave the *.ogg files rather than delete them after converting them to *.mp3 files.  To use the script, I cd to a folder that contains *.ogg files, then I run the script.


$ cd ~/Music
$ ./ogg2mp3.sh

You can make the script as elaborate as you want. Hopefully it was simple enough to give you a feel of how to use the other utilities together: ogginfo, oggdec, id3v2, and lame.

Advertisements