When uploading music to your computer or download it from the internet, sometimes there is a small thumb image shows up instead of the default OS audio icon. Does anybody know how to capture this thumb while upload it to a server?
ID3v2 can also contain images you might say. Well, there is a way to read them.
<?php
require_once 'Zend/Media/Id3v2.php'; // or using autoload
$id3 = new Zend_Media_Id3v2("file.mp3");
header("Content-Type: " . $id3->apic->mimeType);
echo $id3->apic->imageData;
No harder than that!
In a slightly harder example we extract the cover images from a directory full of music files. In this example we first scan the whole directory looking for MP3 files. After ensuring the file contains a valid ID3v2 tag and actually has a cover image, we gather information about the image and write the image data to a separate file, or the same file with an added image suffix.
<?php
require_once 'Zend/Media/Id3v2.php'; // or using autoload
require_once 'Zend/Media/Id3/Exception.php';
$directory = "../change/path/to/mp3/directory/here";
/* Retrieve all files in the directory */
foreach (glob($directory . "/*.mp3") as $file) {
echo "Reading " . $file . "\n";
/* Attempt to parse the file, catching any exceptions */
try {
$id3 = new Zend_Media_Id3v2($file);
}
catch (Zend_Media_Id3_Exception $e) {
echo " " . $e->getMessage() . "\n";
continue;
}
if (isset($id3->apic)) {
echo " Found a cover image, writing image data to a separate file..\n";
/* Write the image */
$type = explode("/", $id3->apic->mimeType, 2);
if (($handle = fopen
($image = $file . "." . $type[1], "wb")) !== false) {
if (fwrite($handle, $id3->apic->imageData,
$id3->apic->imageSize) != $id3->apic->imageSize)
echo " Found a cover image, but unable to write image file: " .
$image . "\n";
fclose($handle);
}
else echo " Found a cover image, but unable to open image file " .
"for writing: " . $image . "\n";
} else
echo " No cover image found!\n";
}
?>
One can run the script from a command prompt or terminal. With a little tuning, one could even take the source directory from the command line arguments.
require_once 'Zend/Media/Id3v2.php'
And that's it. No need to run the rest of the Zend framework.