实现从MP3中提取封面
链接
https://blog.csdn.net/studywithallofyou/article/details/7738785
https://wenku.baidu.com/view/bab750ebb8f67c1cfad6b85a.html
请先查看上方链接内容,以下内容为提起封面实现
<?php
$path = __DIR__.'/../../../public/Approaching Nirvana - You.mp3';
$fp = new \SplFileObject($path,'r');
$fp->fseek(0);
// 标签头
$labelHeader = $fp->fread(10);
// ID3
$header = substr($labelHeader,0,3);
// 版本
$version = substr($labelHeader,3,2);
// 标志
$flags = substr($labelHeader,5,1);
// 大小
$size = substr($labelHeader,6);
// 计算后的标签大小
$labelSize = (ord($size[0]) & 0x7f) * 0x200000 + (ord($size[1]) & 0x7f)
* 0x4000 + (ord($size[2]) & 0x7f) * 0x80 + (ord($size[3]) & 0x7f);
$mp3Info = [];
while ($fp->ftell() < $labelSize){
// 获取帧头信息
$frameHeader = $fp->fread(10);
// 忽略全部都是空的字节
if (!preg_match('/[^\x00]/',$frameHeader)) continue;
$frame = [
// 帧头
'header' => $frameHeader,
// 帧id
'id' => substr($frameHeader,0,4),
// 帧大小
'size_byte' => substr($frameHeader,4,4),
// 帧大小 计算后的
'size' => 0,
// 帧标志
'flags' => substr($frameHeader,8),
// 帧内容
'content' => '',
];
// 计算帧大小
$frame['size'] = ord($frame['size_byte'][0]) * 0x1000000 + ord($frame['size_byte'][1])
* 0x10000 + ord($frame['size_byte'][2]) * 0x100 + ord($frame['size_byte'][3]);
// 读取帧内容
$frame['content'] = empty($frame['size']) ? '' : $fp->fread($frame['size']);
switch (true){
// 图片
case $frame['id'] == 'APIC':
preg_match('/([^\r\n|\n]+)/',$frame['content'],$matches);
$str = explode("\x00",trim($matches[1]));
$imageContent = $str[2].substr($frame['content'],strlen($matches[1]));
$info = getimagesizefromstring($imageContent);
$type = [
0x00 => 'Other',
0x01 => '32x32 pixels \'file icon\' (PNG only)',
0x02 => 'Other file icon',
0x03 => 'Cover (front)',
0x04 => 'Cover (back)',
0x05 => 'Leaflet page',
0x06 => 'Media (e.g. label side of CD)',
0x07 => 'Lead artist/lead performer/soloist',
0x08 => 'Artist/performer',
0x09 => 'Conductor',
0x0A => 'Band/Orchestra',
0x0B => 'Composer',
0x0C => 'Lyricist/text writer',
0x0D => 'Recording Location',
0x0E => 'During recording',
0x0F => 'During performance',
0x10 => 'Movie/video screen capture',
0x11 => 'A bright coloured fish',
0x12 => 'Illustration',
0x13 => 'Band/artist logotype',
0x14 => 'Publisher/Studio logotype'
];
$frame = array_merge($frame,[
'image_mime' => $info['mime'],
'image_type' => $type[ord($str[1])] ?? '',
'width' => $info[0],
'height' => $info[1],
'content' => $imageContent
]);
// 写入文件
// file_put_contents('cover.jpeg',$frame['content']);
break;
// 标题 专辑 作者
case in_array($frame['id'],['TIT2','TALB','TPE1']):
$encodeArray = [
0x00 => 'ISO-8859-1',
0x01 => 'UTF-16',
0x02 => 'UTF-16BE',
0x03 => 'UTF-8',
];
$encode = $encodeArray[ord(substr($frame['content'],0,1))];
if($encode != 'UTF-8'){
$frame['content'] = mb_convert_encoding(substr($frame['content'],1), 'UTF-8', $encode);
}
break;
// ... 其它
}
$mp3Info[$frame['id']] = $frame;
}
$fp = null;
// var_dump($mp3Info);
?>