Five Things You Didn't Know You Could Do with Perl - ' Organize MP3s ' (
Page 4 of 6 )
Organizing your MP3s
If you've moved on from CDs and now have all your music in digital format, then you're probably using the MP3 format to store your music. MP3s are a great way of storing music, but organizing them can be something of a complex process, especially if you want to use them outside of an organized environment like iTunes, WinAMP or MusicMatch Jukebox. Alternatively, you might just be like me, and like to keep your files organized.
Doing it by hand is obviously a nightmare, but we can make use of the MP3 tags; a series of data built into the MP3 file which is used by MP3 players to display the track information. We can use that through Perl using the MP3::Info module to extract the data and then use that as the basis for identifying the album and artist and then file the files into a folder structure. You can see a script for doing this below.
use MP3::Info;
use File::Copy;
use File::Spec::Functions;
use File::Path;
use warnings;
use strict;
foreach my $file (@ARGV)
{
my $tag = get_mp3tag($file);
unless(defined($tag))
{
warn "No tag in $file\n";
next;
}
if (defined($tag->{ALBUM}) && defined($tag->{ARTIST}))
{
my $directory = catfile($tag->{ARTIST},$tag->{ALBUM});
mkpath ($directory,0,0777) unless (-e $directory);
my $newfile = $file;
$newfile =~ s/^(.*\/)?.*?(\d+).*(\.mp3)$/$2$3/;
my $newloc = catfile($directory,$file);
if (move($file,$newloc))
{
printf("Moved %40s to %40s\n",$file,$newloc);
}
else
{
warn "Error: $!\n";
}
}
}
ADVERTISEMENT
For portability, I used standard modules to create folders and paths, and to actually move the file. You should be able to use this script on any platform supported by Perl.