<?php
/**
* php mp3 tagger
* author: stoyandelev.com
*/
class MP3tagger {
/**
* Tags and his regex
*
* @var array
*/
private $tempVars = array(
'<title>' => '([a-zA-Z0-9 ]+)',
'<artist>' => '([a-zA-Z0-9 ]+)',
'<album>' => '([a-zA-Z0-9 ]+)',
'<year>' => '([0-9]+)',
'<track>' => '([0-9]+)');
/**
* Escaped simbols.
*
* @var array
*/
private $escape = array('-'=>'\-', '_' => ' ');
/**
* Song title
*
* @var string
*/
private $title;
/**
* Song artist
*
* @var string
*/
private $artist;
/**
* Song album
*
* @var string
*/
private $album;
/**
* Song year release
*
* @var integer
*/
private $year;
/**
* Song track
*
* @var inteeger
*/
private $track;
/**
* Template with tags
*
* @var string
*/
private $template;
/**
* Set
*
* @param string $key
* @param string $value
*/
function set( $key, $value ) {
$this->$key = $value;
}
/**
* Parse file name and get info based on it
*
* @param string $fileName
*/
function getFileInfo($fileName) {
//get tags
preg_match_all('/<([a-z]+)>/U', $this->template, $tempVars);
$tempVars = $tempVars[1];
$template = $this->template;
//escape special simbols
$template = str_replace(array_keys($this->escape), $this->escape, $template);
//replace temp vars with preg
$template = str_replace(array_keys($this->tempVars), $this->tempVars, $template);
preg_match( '/' . $template . '/', $fileName, $result);
//set info
foreach( $tempVars as $k => $objVar ) {
$this->$objVar = $result[ $k + 1 ];
}
}
/**
* Write information about song
*
* @param string $pathToFile
* @return boolean
*/
function write($pathToFile) {
$fileName = $this->getFileName($pathToFile);
$pregTemp = '' ;
$this->getFileInfo($fileName);
$file = fopen($pathToFile, "r+b");
if( $file == false ) {
return false;
} else {
fseek($file, -128, SEEK_END);
fputs($file, 'TAG', 3);
fputs($file, str_pad($this->title, 30), 30);
fputs($file, str_pad($this->artist, 30), 30);
fputs($file, str_pad($this->album, 30), 30);
fputs($file, str_pad($this->year, 4), 4);
fputs($file, str_pad('', 28), 28);
fputs($file, str_pad(chr('null'), 1), 1);
fputs($file, str_pad(chr($this->track), 1), 1);
}
fclose($file);
return true;
}
/**
* Get file name
*
* @param String $pathToFile
* @return String
*/
function getFileName($pathToFile) {
$file = end( explode('/', $pathToFile) );
return $file;
}
}
$ob = new MP3tagger();
$ob->set('artist', 'The Verve');
$ob->set('album', 'Urban Hymns');
$ob->set('year', '1993');
$ob->set('template', '<track> - <title>');
//echo $ob->read('CD1/01 - Space Oddity.mp3');
$dir = '2003 - Urban Hymns/';
$files = scandir($dir);
foreach( $files as $f ){
if( $f != '.' AND $f != '..' ) {
$ob->write( $dir . $f );
}
}
?>