Reading MP3 file tags in PHP


Posted in: pear | Save to del.icio.us | Twit This! 7 Dec 2009

I recently had a small task to scan some MP3 files on a server to check whether the files had any metadata in them, and add them if necessary. All MP3’s have a metadata section that allows information such as the title, artist, album, track number etc. to be stored in the MP3 file itself. The metadata is stored in the ID3 format. Of course I could have used a desktop tag editor, but the files where on the server, which frequently kept changing. So a server solution was the only way to go.

For the solution I used the Pear MP3_Id package. There are many PHP libraries around that support manipulation of MP3 metadata, but this one was the one I narrowed down. The following examples show how you can use the package to manipulate mp3’s metadata.

Installing MP3_Id

MP3_Id being a Pear package we will use the Pear installer. Or you can manually download the package from Pear MP3_Id.

pear install MP3_Id-1.2.1

Reading mp3 tags

The following function reads the ID3v1 data from all the mp3 files in the given directory, returning the data as an array.

<?php
 
require_once("MP3/Id.php");
 
function read_mp3_tags($dir)
{
    static $result = array();
    static $i = 0;
 
    $tag_string = "";
 
    $mp3 = &new MP3_Id();
 
    // Tags supported by the MP3_Id class
    $tags = array(
                  "name", "artists", "album",
                  "year", "comment", "track",
                  "genre", "genreno"
                  );
 
 
    // Read the current directory
    $d = dir($dir);
 
    // Loop through all the files in the current directory:
    while (false !== ($file = $d->read()))
    {
        // Skip '.' and '..'
        if (($file == '.') || ($file == '..'))
        {
            continue;
        }
 
        // If this is a directory, then recursively call it
        if (is_dir("{$dir}/{$file}"))
        {
            read_mp3_tags("{$dir}/{$file}");
        }
        else
        {
            // It's a mp3 file so read the tags
            if(strtolower(substr($file, strlen($file) - 3, 3)) == "mp3") 
            {
                $data = $mp3->read("{$dir}/{$file}");
 
                // OOPs, some error occured, just save the filename
                if (PEAR::isError($data))
                { 
                    $result[$i]['filename'] = $file;
                    $result[$i]['directory'] = $dir;
                }
                else
                {
                    $result[$i]['filename'] = $file;
                    $result[$i]['directory'] = $dir;
 
                    // Read all the tags of the particular file
                    foreach($tags as $tag)
                    {
                        $result[$i][$tag] = $mp3->getTag($tag);
                    }
                }
                $i++;
            }
        }
    }
 
    return $result;
}
 
 
// Call the above function on your mp3 directory
$results = read_mp3_tags(PATH_TO_YOUR_MP3_DIRECTORY);
print_r($results);
 
?>

Writing or updating tags in an MP3

After you have read ID3 tags, you may want to change or add some new tag information to the files. The following code for example adds the missing album name to the ID3 metadata.

Before you modify any files, be sure you backup them until you are sure your code works fine.

<?php
 
require_once("MP3/Id.php");
 
$mp3 = &new MP3_Id();
 
// Read the MP3 file
$mp3->read("Tears For Fears - Shout.mp3");
 
// Add the album name to the 'album' tag
$mp3->setTag("album", "Songs from the Big Chair");
 
// This is essential. We need to write back the changes
$mp3->write();
 
?>

If you have duplicate files of the same song, you can also quickly copy tags from one file to the other.

<?php
 
require_once("MP3/Id.php");
 
$mp3_1 = &new MP3_Id();
$mp3_2 = &new MP3_Id();
 
$mp3_1->read("Tears For Fears - Shout.mp3");
$mp3_2->read("Tears For Fears.mp3");
 
// Copy tags from 'Tears For Fears - Shout.mp3' to 'Tears For Fears.mp3'
$mp3_2->copy($mp3_1);
$mp3_2->write();
 
?>

Some other PHP libraries for ID3 manipulation

http://code.google.com/p/php-reader/wiki/ID3v2
http://getid3.sourceforge.net/

Download Source
Downloads : 119 / File size : 925 B



Share this post

Share on Facebook
Share on Twitter
Share on StumbleUpon
Share on Delicious
Share on Digg
Share on Technorati
Share on Reddit
Feeds RSS Subscribe to site Feed

Other related posts

  • No Related Post


Comment Form

Use the html <code> tag to insert small source code snippets

For longer code examples use http://pastie.org/.

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

Recent Comments

  • sameer: My apologies! I'm not conversant with SharePoint. [...]
  • avanthi: Is it possible to automate share point people picker control through selenium. When i record throug [...]
  • sameer: Check to see if the 'IDE > options > format' is set to HTML. [...]
  • sameer: Google strips any newline characters form the text. Although it does accept it with the online trans [...]
  • Arjan: Fiddler is a debugging tool for IE (not Microsoft's Fiddler) [...]
  • Susan Martin: while creating a test for site, command icons on IDE greyed out and do not respond when selected. I [...]
  • Saar: Thanks for this example. helped me a lot. I have 1 problem, I am translating chunks of code, but I [...]
  • sameer: You can add extra GET variables in the options array as below: $pager_options = array( 'mode [...]

  • Users Online

    • 9 Users Online
    • 8 Guests, 1 Bot