Oct
29

Converting WMA files to MP3 on Linux (specifically Ubuntu) and retain tag information

I recently needed to convert a bunch of (DRM-free) WMA files to MP3 format on Ubuntu, and there’s no good tool out there to do it.  There are plenty of tutorials that tell you how to convert from WMA to WAV with Lame, then from WAV to MP3 with mplayer, but none of these tutorial talk about how that will cause you to lose all the WMA artist/album/title data.  I needed a tool that would keep the tagged data;  so, I made one.  It requires mplayer, lame, and mutagen-inspect, all of which are available from aptitude.

So, here’s my script: wma2mp3

Usage: wma2mp3 in-wma out-mp3

#!/bin/bash
IN=$1
O=${2-${IN%\.wma}}
OUT=${O%\.mp3}.mp3
TEMP=`mktemp /tmp/convert.XXXXX.wav`
 
echo Converting \"$IN\" to \"$TEMP\"
mplayer -vc null -vo null -ao pcm:waveheader:fast:file=%`expr length "$TEMP"`%"$TEMP"  "$IN"
 
echo Converting $TEMP to $OUT
lame "$TEMP" "$OUT"
rm $TEMP
echo Fixing ID3 tags
ARTIST=`mutagen-inspect "$IN" |  grep WM/AlbumArtist  | grep -E --only-matching "[^=]+$"`
ALBUM=`mutagen-inspect "$IN" |    grep WM/AlbumTitle  | grep -E --only-matching "[^=]+$"`
NUM=`mutagen-inspect "$IN" |    grep WM/TrackNumber  | grep -E --only-matching "[^=]+$"`
TITLE=`mutagen-inspect "$IN" |   grep -E "^Title=" | grep -E --only-matching "[^=]+$"`
echo Artist = \"$ARTIST\"
echo Album = \"$ALBUM\"
echo Track Number = \"$NUM\"
echo Title = \"$TITLE\"
mp3info -a "$ARTIST" -l "$ALBUM"    -n "$NUM" -t "$TITLE" "$OUT"
echo Done!

Edit: Thanks to a post over on reddit, here’s an update that makes better use of shell scripting:

#!/bin/sh
 
in=$1
out=${in%.[Ww][Mm][Aa]}.mp3
 
mutagen-inspect "$in" | {
    while IFS= read -r tag; do
        case $tag in
        WM/AlbumArtist*)
            ARTIST=${tag#*=}
            ;;
        WM/AlbumTitle*)
            ALBUM=${tag#*=}
            ;;
        WM/TrackNumber*)
            NUM=${tag#*=}
            ;;
        Title=*)
            TITLE=${tag#*=}
            ;;
        esac
    done
 
    mplayer -vc null -vo null -ao pcm:waveheader:fast:file=/dev/stdout |
    lame --tt "$TITLE" --ta "$ARTIST" --tl "$ALBUM"  --tn "$NUM" - "$out"
}

2 Comments to “Converting WMA files to MP3 on Linux (specifically Ubuntu) and retain tag information”

  • cybermagnetik May 31, 2011 at 1:40 am

    What a great web log. I spend hours on the net reading blogs, about tons of various subjects. I have to first of all give praise to whoever created your theme and second of all to you for writing what i can only describe as an fabulous article. I honestly believe there is a skill to writing articles that only very few posses and honestly you got it. The combining of demonstrative and upper-class content is by all odds super rare with the astronomic amount of blogs on the cyberspace.

  • sniffer March 29, 2015 at 2:49 pm

    this also preserve id3tags:

    ffmpeg -i [file.wma] -acodec libmp3lame -ab 128k [file.mp3]

Post comment

%d bloggers like this: