GetID3

GetID3 is a PHP library for parsing and manipulating ID3 tags in MP3 audio files. It is notable for its dearth of friendly documentation, though many useful tidbits can be found in the GetID3 forums.

Reading and writing artist, title, genre, etc. tags

A listing of the data structure returned by GetID3 is found in the structure.txt document.

Reading a track’s ID3 tags should be a matter of doing something like the following:

$getID3 = new getID3;
$getID3->analyze($filename);

And then looking at the contents of $getID3->info (detailed in the link above).

Writing ID3 tags seems a bit hazardous, because, evidently, any write operation rewrites all existing ID3 tags. So if you want to preserve any existing tags, you must read them first and then be careful to write them back along with any changes you’re trying to make.

Further documentation on this to be added later if I ever end up needing it.

Reading album cover art

Album cover art is stored in a tag field called APIC, or possibly PIC (not sure about this). The image type is stored in a subfield as a MIME type (e.g., “image/jpeg,” “image/png,” etc.).

Basic code for extracting cover art looks like this:

$getID3 = new getID3;
#$getID3->option_tag_id3v2 = true; # Don't know what this does yet
$getID3->analyze($filename);
if (isset($getID3->info['id3v2']['APIC'][0]['data'])) {
    $cover = $getID3->info['id3v2']['APIC'][0]['data'];
} elseif (isset($getID3->info['id3v2']['PIC'][0]['data'])) {
    $cover = $getID3->info['id3v2']['PIC'][0]['data'];
} else {
    $cover = null;
}
if (isset($getID3->info['id3v2']['APIC'][0]['image_mime'])) {
    $mimetype = $getID3->info['id3v2']['APIC'][0]['image_mime'];
} else {
    $mimetype = 'image/jpeg'; // or null; depends on your needs
}

Note that the variable $getID3->info['id3v2']['APIC'] in the above code sample is an array. The above code assumes that you only care about the first image in the array, but others could be present. iTunes, for example, allows multiple images to be embedded in a track.

The following code can be used to directly output the cover image stored in $cover:

if (!is_null($cover)) {
    // Send file
    header("Content-Type: " . $mimetype);
    if (isset($getID3->info['id3v2']['APIC'][0]['image_bytes'])) {
        header("Content-Length: " . $getID3->info['id3v2']['APIC'][0]['image_bytes']);
    }
    #header("Content-Transfer-Encoding: binary"); # Possibly unnecessary
    echo($cover);
}

For performance reasons, however, you’re usually better off extracting the image beforehand and saving it to a static image file rather than extracting and displaying it dynamically.

[ article last updated 2007-02-22 14:51:39 by cobra libre ]