1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Read ID3 tag from a MP3 file

Discussion in 'PHP' started by pradeep, Apr 10, 2005.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Here's the code to read ID3 tage from a MP3 file


    PHP:
    <?php
     
     
    //Reads ID3v1 from a MP3 file and displays it
     
     
         
    $mp3 "1.mp3"//MP3 file to be read
     
                     //make a array of genres
         
    $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("1.mp3""r");
         
    fseek($file, -128SEEK_END);
         
         
    $tag fread($file3);
         
         
         if(
    $tag == "TAG")
         {
             
    $data["song"] = trim(fread($file30));
             
    $data["artist"] = trim(fread($file30));
             
    $data["album"] = trim(fread($file30));
             
    $data["year"] = trim(fread($file4));
             
    $data["comment"] = trim(fread($file30));
             
    $data["genre"] = $genre_arr[ord(trim(fread($file1)))];
             
         }
         else
             die(
    "MP3 file does not have any ID3 tag!");
         
         
    fclose($file);
         
         while(list(
    $key$value) = each($data))
         {
             print(
    "$key$value<br>\r\n");    
         }
         
         
     
     
    ?>
     
    Last edited by a moderator: Apr 11, 2005
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83
    I am not that expert in PHP but I think this is nice peace of code. but when I run the code with different mp3 files I get the message

    MP3 file does not have any ID3 tag!

    Can you tell me what the ID3 tag is all about and how I can have a file that have ID3 tag.

    Thanks
    Shabbir Bhimani
     
    Last edited: Apr 10, 2005
  3. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    After the birth of the MP3 file format, there remained a problem, which was inclusion of textual information i.e. some information about the audio file.At that time a person named Eric Kemp alias NamkraD suggested a fixed-size 128 byte tag inside a MP3 file which would include would include title, artist, album, year, genre and a comment field. And this person himself implemented his idea and people welcomed it with open arms. Not much later Michael Mutschler, extended this tag which is called ID3 tag. He named his version ID3 v1.1. The current version of ID3 is v2.2.
    You can read more about ID3 here http://www.id3.org/intro.html

    Most of the CD ripping softwares include a custom or a default ID3 tag, but just in case your MP3 file does have an ID3 tag there are a plethora of software which will do it for you. The most famous, simple and easily available being Winamp, which has an in-built ID3 editor. In the Winamp playlist window just right-click on the playlist item whose ID3 tag you want edit, and select File Info, and you'll get a dialog box where you can input all the info about the song.

    Some ID3 editors:
    http://www.handyarchive.com/Audio/MP3-Organizers/575-AB-MP3-Tag-Editor.html
    http://www.handyarchive.com/Audio/Music-Management/16020-Music-Xpert-Tag-Editor.html

    Enjoy,
    Pradeep.
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83
    OK

    Yes I use that but thought that they keep it in seperate file but now I knew that they use the same file to store the data about the file.
     
  5. shaiss

    shaiss New Member

    Joined:
    Dec 21, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    thank you for the code.
    This helped me greatly.
    However I am now trying to loop through a directory and get the id3 tag of each file in that directory.

    Here's my code
    Code:
    <HTML>
    <HEAD>
     <TITLE>MP3 Playlist</TITLE>
    </HEAD>
    <BODY>
    <?php
    
    //Declarations
    $dir = "/private/var/root/Media/iTunes_Control/Music/F00";
    //$mp3 = "/private/var/root/Media/iTunes_Control/Music/F00/YSDN.mp3"; //MP3 file to be read
    
                     //make a array of genres
        $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");
    
    //$dir = getcwd() . "\n";
    
    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($fileread = readdir($dh)) !== false) {
                //show the file name and location
                $fullpath = $dir . $fileread;
                echo "filename: <b>$fullpath</b>";
                echo "<br>";
    
                //Get the ID3 Tag info
                $musicfile = $fullpath; //fopen($fullpath, "r");
                fseek($musicfile, -128, SEEK_END);
                
                $tag = fread($musicfile, 3);
                
                if($tag == "TAG")
                {
                $data["song"] = trim(fread($musicfile, 30));
                $data["artist"] = trim(fread($musicfile, 30));
                $data["album"] = trim(fread($musicfile, 30));
                $data["year"] = trim(fread($musicfile, 4));
                $data["comment"] = trim(fread($musicfile, 30));
                $data["genre"] = $genre_arr[ord(trim(fread($musicfile, 1)))];
                }
                else
                        die("MP3 file does not have any ID3 tag!");
    
                fclose($musicfile);
    
                while(list($key, $value) = each($data))
                    {
                    print("$key: $value<br>\r\n");
                    }
            }
        }
    }
    //echo getcwd() . "\n";
    //echo $sCwd = (substr(PHP_OS, 0, 3) == 'WIN') ? strtolower(getcwd()) : getcwd();
    ?>
    </BODY>
    </HTML>
    
    when you try to run it you get the following error:
    Code:
    filename: /private/var/root/Media/iTunes_Control/Music/F00.
    
    Warning: fseek(): supplied argument is not a valid stream resource in /private/var/root/Sites/getid3.php on line 49
    
    Warning: fread(): supplied argument is not a valid stream resource in /private/var/root/Sites/getid3.php on line 51
    MP3 file does not have any ID3 tag!
    
    any ideas why?
     
  6. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    You are trying to use fseek without opening the file.
     
  7. GreatGatsby

    GreatGatsby New Member

    Joined:
    Jun 10, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    shaiss,

    Did you get this working? I am trying to do the exact same thing you are.
     
  8. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    I had run this on Windows, it worked perfectly!
     
  9. danwoods

    danwoods New Member

    Joined:
    Aug 6, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Any idea how to get the length of the audio using your basic code?
     
  10. ramandeep000

    ramandeep000 New Member

    Joined:
    Jul 6, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    ludhiana
    Home Page:
    You can Get Mp3 Tags without fully downloading the File.WE download file in chunks ,WE extract first and last 64 kb of the file Using ID3 PHP library and CURL.
    I have created a function that will do that
    Download id3 library and include it in your script .
    PHP:
    require_once("id3/getid3.php");
    function 
    getfileinfo($remoteFile)
    *
    {
    *
    $url=$remoteFile;
    $uuid=uniqid("designaeon_"true);
    *
    $file="temp/".$uuid.".mp3";
    *
    $size=0;
    *
    $ch curl_init($remoteFile);
    *
    //==============================Get Size==========================//
    *$contentLength 'unknown';
    *
    $ch1 curl_init($remoteFile);
    *
    curl_setopt($ch1CURLOPT_NOBODYtrue);
    *
    curl_setopt($ch1CURLOPT_RETURNTRANSFERtrue);
    *
    curl_setopt($ch1CURLOPT_HEADERtrue);
    *
    curl_setopt($ch1CURLOPT_FOLLOWLOCATIONtrue); //not necessary unless the file redirects (like the PHP example we're using here)
    *$data curl_exec($ch1);
    *
    curl_close($ch1);
    *if (
    preg_match('/Content-Length: (\d+)/'$data$matches)) {
    *
    $contentLength = (int)$matches[1];
    *
    $size=$contentLength;
    *}
    *
    //==============================Get Size==========================//
    *
    *if (!
    $fp fopen($file"wb")) {
    *echo 
    'Error opening temp file for binary writing';
    *return 
    false;
    *} else if (!
    $urlp fopen($url"r")) {
    *echo 
    'Error opening URL for reading';
    *return 
    false;
    *}
    *try {
    *
    $to_get 65536// 64 KB
    *$chunk_size 4096// Haven't bothered to tune this, maybe other values would work better??
    *$got 0$data null;
    *
    *
    // Grab the first 64 KB of the file
    *while(!feof($urlp) && $got $to_get) {
    *
    $data $data fgets($urlp$chunk_size);
    *
    $got += $chunk_size;
    *}
    *
    fwrite($fp$data);
    *
    *
    // Grab the last 64 KB of the file, if we know how big it is.
    *if ($size 0) {
    *
    curl_setopt($chCURLOPT_FILE$fp);
    *
    curl_setopt($chCURLOPT_HEADER0);
    *
    curl_setopt($chCURLOPT_RESUME_FROM$size $to_get);
    *
    curl_exec($ch);
    *}
    *
    *
    // Now $fp should be the first and last 64KB of the file!!
    *
    @
    fclose($fp);
    *@
    fclose($urlp);
    *} catch (
    Exception $e) {
    *@
    fclose($fp);
    *@
    fclose($urlp);
    *echo 
    'Error transfering file using fopen and cURL !!';
    *return 
    false;
    *}
    *
    $getID3 = new getID3;
    *
    $filename=$file;
    *
    $ThisFileInfo $getID3->analyze($filename);
    *
    getid3_lib::CopyTagsToComments($ThisFileInfo);
    *
    unlink($file);
    *return 
    $ThisFileInfo;
    }
    You can get Full tuet on here...
    hxxp://designaeon.com/read-mp3-tags-without-downloading-it/
     
  11. cyclop

    cyclop New Member

    Joined:
    Nov 20, 2012
    Messages:
    13
    Likes Received:
    0
    Trophy Points:
    0
    Thanks for this. I was looking for something similar to read metadata in images :)
     

Share This Page