Friday, July 31, 2009

Rip from WAV to MP3 and add ID3 tags -- All with Perl

Ok - so I know I have said before that I am not much of a perl fan. ( yes it's safe, I am wearing my flame proof suit. )

I will, however, say now; I am coming around. It would seem that I am starting to see the light. I needed to extract some files from a CD I have and convert them to MP3. The CD was not made with extracting to mp3 in mind if you get my drift. It's ok, because the CD is my copy and I want to listen to it on my iPod. Regular extracting on iTunes was not working out for me. So I rolled my chair over to my trusty Linux Box and perl, id3, cdparanoia and lame.

First thing I did was use cdparanoia to extract all the tracks. This went swimmingly leaving me with a folder full of files called 01.cdparanoia.wav or something just as useless. The files played ok but I needed to name them all. This particular CD was not listed on Music Brainz so I couldn't do anything fancy with FreeCDDB or whatever they call that now days.

* shudder * - I had to manually edit 17 filenames. I left the .wav extensions of course. I thought that I might need to get the tags later so I decided to choose a naming scheme for my file names.

01-My Song Title_My Artist Name.wav

and so on.

Then I wrote a little script that:
  • Loops through each file in a folder with the .wav extension
  • Saves a variable with the file name but with .mp3 instead of .wav
  • Regexes ( new word ) out the various parts of the file name into $track, $title, $artist ( thanks to the nice naming scheme this was easy. )
  • Uses Lame to convert the file. Lame now days is pretty cool.
  • Uses id3v2 to add the tags extracted from the file name. I can use amarok to add the album titles etc once it is imported into Amarok.
Here is the script:
#!/usr/bin/env perl

@files = <*.wav>;

foreach $file (@files) {

$newfile = $file;
$newfile =~ s/\.wav/\.mp3/;

$file =~ m/^(.*)-(.*)_(.*).wav/;

$track = $1;
$title = $2;
$artist = $3;

system("lame", "--preset", "cd" ,"$file" ,"$newfile");
system("id3v2", "--artist", "$artist", "$newfile");
system("id3v2", "--song", "$title", "$newfile");
system("id3v2", "--track", "$track", "$newfile");


1 comment:

interval said...

Nice script, like the display during processing. I tried using Grip but it kept complaining about not finding lame or cdparanoia (even though they are obviously installed). Always go command line when in doubt.