PHP 获取MP3信息(时长、ID3标签、码率、封面)3种方案
方案 1:getID3(推荐,最全能,解析 ID3v1/v2、时长、采样、封面)
1. 安装
composer require james-heinrich/getid3
2. 使用代码
<?php
require 'vendor/autoload.php';
$getID3 = new getID3();
$file = 'test.mp3';
$info = $getID3->analyze($file);
getID3_lib::CopyTagsToComments($info);
// 基本信息
$duration = $info['playtime_seconds']; // 总秒数
$bitrate = round($info['audio']['bitrate']/1000); // kbps
$sample = $info['audio']['sample_rate']; //采样率
// ID3标签(歌名、歌手、专辑)
$title = $info['comments']['title'][0] ?? '';
$artist = $info['comments']['artist'][0] ?? '';
$album = $info['comments']['album'][0] ?? '';
// 提取封面图片
if(!empty($info['comments']['picture'][0]['data'])){
$cover = $info['comments']['picture'][0]['data'];
file_put_contents('cover.jpg',$cover);
}
var_dump([
'时长秒'=>$duration,
'码率kbps'=>$bitrate,
'歌名'=>$title,
'歌手'=>$artist
]);
方案 2:FFmpeg 解析(无 ID3 也能精准取时长,服务器需装 FFmpeg)
<?php
$mp3 = 'test.mp3';
$cmd = "ffmpeg -i {$mp3} 2>&1";
$res = shell_exec($cmd);
// 匹配时长
preg_match('/Duration:\s(\d+):(\d+):(\d+)/',$res,$dur);
if($dur){
$h=$dur[1];$m=$dur[2];$s=$dur[3];
$total = $h*3600+$m*60+$s;
echo '总秒数:'.$total;
}
安装 FFmpeg:apt install ffmpeg(debian) /yum install ffmpeg(centos)
方案 3:PHP 内置 ID3 扩展(仅读取 ID3 标签,无法精准时长,不推荐)
<?php
// 需开启id3扩展
$tag = id3_get_tag('test.mp3');
print_r($tag);
常用字段汇总
| 参数 | 说明 |
|---|---|
| playtime_seconds | 音频总秒数 |
| audio'bitrate' | 比特率 (bps)/÷1000=kbps |
| sample_rate | 采样率 44100/48000 |
| comments'picture' | 专辑封面二进制 |
0
1