MP3 Folderizer

June 10, 2004, updated July 30, 2004

Say you have a whole bunch of MP3 files into a directory and you want to sort them all into directories based on author.

While pretty rudimentary, this script does about all I need.

This PHP script will search for a "-" and consider everything before that in the filename the author. So make sure you name your files in the author-song.mp3 format. It will then proceed to move the file to its respective author named folder. If it does not exist, the script will create it them move it there. If the file already exists in the folder, it will simply move it to a duplicates folder. Handy little script that saved me a lot of time.
#!/usr/bin/php
<?
/*
    MP3 Folderizer
    Copyright (C) 2004  J.D. Henderson <www.digitalpeer.com>
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
 
function mvtodir($dir,$file)
{
	$artist = getartist($file);
 
	echo "Moving file $file with artist $artist ...n";
 
	// if we can't get a artist just skip the file
	if ($artist == "")
	{
		echo "Error: Improperly named file: $filen";
		return;
	}
 
	// see if there is already a folder and make it if not
	if (!file_exists($dir."/".$artist))
	{
		echo "New artist directory created: $artistn";
		mkdir($dir."/".$artist);
	}
 
	/*
	if the file already exists then don't move it there
	if the existing file is the same, move it to the duplicates folder
	*/
	if (file_exists($dir."/".$artist."/".$file))
	{
		echo "File $file already exists in folder $artistn";
		return;
	}
	else
	{
		echo "Moving $file to folder $artistn";
		rename($dir."/".$file, $dir."/".$artist."/".$file);
	}
}
 
function getartist($file)
{
	$fileparts = explode('-',$file);
	if (count($fileparts) != 2)
		return "";
 
	return ltrim(rtrim($fileparts[0]));
}
 
function folderize($dir)
{
	$files = array();
	$h=opendir($dir);
	while (false !== ($file = readdir($h)))
	{
		if(is_dir($dir."/".$file))
			continue;
		else if (ereg(".mp3$", strtolower($file)))
		{
			mvtodir($dir,$file);
		}
	}
	closedir($h);
}
 
if ($argc != 2)
	echo "Usage: ".$argv[0]." <root_mp3_dir>n";
else
	folderize($argv[1]);
 
?>

Related Posts

1 Comment

Comment July 20, 2005 by <P>
Hi there, there actually is a much easier way to do this: blog.jardas.de/2005/07/13/mp3-folderize-script-2/ Cheers, <P>