Last update: 2011-03-02 02:14:37
Si comme moi vous avez une grosse collection de disques que vous encodez pour votre baladeur et/ou que vous achetez beaucoup de mp3s, le rangement de ces fichiers doit être un cauchemar... afin d'y remédier je me suis fait un petit script "quick and dirty" mais qui "fait le job" comme disent les anglophones. Basé sur la librairie getID3 qui'il vous faudra évidemment ajouter à votre include_path:
#!/usr/bin/php5
< ?php
// destination !
define('SND_PATH','/media/usb0/mytunes/');
// source !
define('IMPORT_PATH','/home/me/bazar/');
mb_internal_encoding('UTF-8');
ini_set('default_charset','utf-8');
require('getid3/getid3.php');
$id3 = new getID3;
function walk_dir( $root, $callback, $recursive = true )
{
$root = realpath($root);
$dh = @opendir( $root );
if( false === $dh )
{
return false;
}
while(false !== ($file = readdir($dh)))
{
if( "." == $file || ".." == $file )
{
continue;
}
call_user_func( $callback, "{$root}/{$file}" );
if( false !== $recursive && is_dir( "{$root}/{$file}" ))
{
walk_dir( "{$root}/{$file}", $callback, $recursive );
}
}
closedir($dh);
return true;
}
function store_mp3($file)
{
global $id3;
// standards anyone ?
$mimes = array(
'audio/mpeg',
'audio/x-mpeg',
'audio/mp3',
'audio/x-mp3',
'audio/mpeg3',
'audio/x-mpeg3',
'audio/mpg',
'audio/x-mpg',
'audio/x-mpegaudio',
'application/ogg',
'application/x-ogg'
);
$mimetype = mime_content_type($file);
if(in_array($mimetype,$mimes))
{
$infos = $id3->analyze($file);
getid3_lib::CopyTagsToComments($infos);
$artist = getLabels($infos['comments']['artist'][0]);
$album = getLabels($infos['comments']['album'][0]);
$title = getLabels($infos['comments']['title'][0]);
if($artist == 'unkown' or $title == 'unknown')
{
echo("\nNot importing '$file', not enough infos.");
return false;
}
$new_path = SND_PATH.$artist{0}.'/'.$artist.'/'.$album.'/'.$title.'.mp3';
// don't overwrite existing files
if(is_file($new_path))
{
if(sha1_file($new_path) == sha1_file($file))
{
echo("\nNot importing '$file', file already exists.");
unlink($file);
return false;
}
else
{
$i = 1;
while(is_file($new_path))
{
$new_path = SND_PATH.$artist{0}.'/'.$artist.'/'.$album.'/'.$title.'_'.$i.'.mp3';
$i++;
}
}
}
if(!is_dir(dirname($new_path)))
{
mkdir(dirname($new_path),0755,true);
usleep(50000);
}
echo("\nImporting '$file'.");
if(copy($file,$new_path))
{
unlink($file);
return true;
}
return false;
}
}
function getLabels($label)
{
$label = trim($label);
if(empty($label))
{
return 'unknown';
}
$encoding = mb_detect_encoding($label,array('ISO-8859-1','UTF-8'),true);
if($encoding == 'ISO-8859-1')
{
$label = utf8_encode($label);
}
return ereg_replace("[^A-Za-z0-9_-]","_",utf2ascii($label));
}
function utf2ascii($utf8_string)
{
$ascii_string= strtr(utf8_decode($utf8_string),utf8_decode("ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ"), "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn");
return $ascii_string;
}
walk_dir(IMPORT_PATH,'store_mp3');
system('mpc update');
echo("\n");