Saturday, March 5, 2011

Extract details from a MP3 file, ID3 Tags

Hi,

In this post, code that I have given below will let you extract the basic information(ID3 tags) from a simple mp3 file. This is not a very advanced version, but it will serve the purpose. The idea is very simple, the details of the music files are appended at the end of the file content. We just need to extract those using fread(). The thing you need to know is what data is stored at what location.

Create a file "example.php" and copy and paste the following code:


<?php
$mp3 = "song.mp3";

$genre_arr = array("Blues","Classic Rock","Country","Dance","Disco","Funk","Grunge", "Hip-Hop","Jazz","Metal","New Age","Oldies","Other","Pop","R&B", "Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska", "Death Metal","Pranks","Soundtrack","Euro-Techno","Ambient", "Trip-Hop","Vocal","Jazz+Funk","Fusion","Trance","Classical", "Instrumental","Acid","House","Game","Sound Clip","Gospel", "Noise","AlternRock","Bass","Soul","Punk","Space","Meditative", "Instrumental Pop","Instrumental Rock","Ethnic","Gothic", "Darkwave","Techno-Industrial","Electronic","Pop-Folk", "Eurodance","Dream","Southern Rock","Comedy","Cult","Gangsta",
 "Top 40","Christian Rap","Pop/Funk","Jungle","Native American", "Cabaret","New Wave","Psychadelic","Rave","Showtunes","Trailer",
 "Lo-Fi","Tribal","Acid Punk","Acid Jazz","Polka","Retro", "Musical","Rock & Roll","Hard Rock","Folk","Folk-Rock", "National Folk","Swing","Fast Fusion","Bebob","Latin","Revival", "Celtic","Bluegrass","Avantgarde","Gothic Rock","Progressive Rock",
 "Psychedelic Rock","Symphonic Rock","Slow Rock","Big Band", "Chorus","Easy Listening","Acoustic","Humour","Speech","Chanson",
 "Opera","Chamber Music","Sonata","Symphony","Booty Bass","Primus", "Porn Groove","Satire","Slow Jam","Club","Tango","Samba",
 "Folklore","Ballad","Power Ballad","Rhythmic Soul","Freestyle", "Duet","Punk Rock","Drum Solo","Acapella","Euro-House","Dance Hall");


$filesize = filesize($mp3);
$file = fopen($mp3, "r");
fseek($file, -128, SEEK_END);
$tag = fread($file, 3);
  
 if($tag == "TAG")
 {
$data["Song Title"] = trim(fread($file, 30));
$data["Artist"] = trim(fread($file, 30));
$data["Album"] = trim(fread($file, 30));
$data["Year Released"] = trim(fread($file, 4));
$data["Comments"] = trim(fread($file, 30));
$data["Genre"] = $genre_arr[ord(trim(fread($file, 1)))];

 }
 else
die("MP3 file does not have any ID3 tag!");

 $data["Size"] = number_format($filesize/(1024*1024),2) ." MB";
 fclose($file);
 echo '<pre>';
 print_r($data);
 echo '</pre>';
  ?>

Copy and past a song.mp3 file in the same directory and execute the code. The output will be something like this:



Cheers!!

2 comments: