您现在的位置是: 首页  >  IT编程

PHP获取音频文件的相关信息

程序员文章站 2022-06-16 09:34:30
项目需求:现在有一个音频文件上传的功能,在上传后php需要获取这个音频文件的相关信息,例如:时长等,由于这个文件是放在买的空间上的,没有像ffmpeg这样的扩展来处理,那么...

项目需求:现在有一个音频文件上传的功能,在上传后php需要获取这个音频文件的相关信息,例如:时长等,由于这个文件是放在买的空间上的,没有像ffmpeg这样的扩展来处理,那么php能不能获取到这些信息?

下面是之前在项目中用到的一个用php进行音频文件头部信息的读取与写入操作的实现,主要针对 wma 和 mp3 两种格式,供参考。

<?php
// audioexif.class.php
// 用php进行音频文件头部信息的读取与写入
// 目前只支持 wma 和 mp3 两种格式, 只支持常用的几个头部信息
//
// 写入信息支持: title(名称), artist(艺术家), copyright(版权), description (描述)
// year(年代), genre (流派), albumtitle (专辑标题)
// 其中 mp3 和 wma 略有不同, 具体返回的信息还可能更多, 但只有以上信息可以被写入
// mp3 还支持 track (曲目编号写入)
// 对于 mp3 文件支持 id3v1也支持id3v2, 读取时优先 v2, 写入时总是会写入v1, 必要时写入v2
//
// 用法说明: (由于 wma 使用 unicode 存取, 故还需要 mb_convert_encoding() 扩展
// 返回数据及写入数据均为 ansi 编码, 即存什么就显示什么 (中文_gb2312)
//
// require ('audioexif.class.php');
// $ae = new audioexif;
// $file = '/path/to/test.mp3';
//
// 1. 检查文件是否完整 (only for wma, mp3始终返回 true)
//
// $ae->checksize($file);
//
// 2. 读取信息, 返回值由信息组成的数组, 键名解释参见上方
//
// print_r($ae->getinfo($file));
//
// 3. 写入信息, 第二参数是一个哈希数组, 键->值, 支持的参见上方的, mp3也支持 track
// 要求第一参数的文件路径可由本程序写入
// $pa = array('title' => '新标题', 'albumtitle' => '新的专辑名称');
// $ae->setinfo($file, $pa);
//
// 其它: 该插件花了不少时间搜集查找 wma及mp3 的文件格式说明文档与网页, 希望对大家有用.
// 其实网上已经有不少类似的程序, 但对 wma 实在太少了, 只能在 win 平台下通过 m$ 的
// api 来操作, 而 mp3 也很少有可以在 unix/linux 命令行操作的, 所以特意写了这个模块
//
// 如果发现 bug 或提交 patch, 或加以改进使它更加健壮, 请告诉我.
// (关于 id3和wma的文件格式及结构 在网上应该都可以找到参考资料)
//
if (!extension_loaded('mbstring')){
trigger_error('php extension module `mbstring` is required for audioexif', e_user_warning);
return true;
}
// the main class
class audioexif{
// public vars
var $_wma = false;
var $_mp3 = false;
// construct
function audioexif() {
// nothing to do
}
// check the filesize
function checksize($file) {
$handler = &$this->_get_handler($file);
if (!$handler) return false;
return $handler->check_size($file);
}
// get the infomations
function getinfo($file) {
$handler = &$this->_get_handler($file);
if (!$handler) return false;
return $handler->get_info($file);
}
// write the infomations
function setinfo($file, $pa) {
if (!is_writable($file)) {
trigger_error('audioexif: file `' . $file . '` can not been overwritten', e_user_warning);
return false;
}
$handler = &$this->_get_handler($file);
if (!$handler) return false;
return $handler->set_info($file, $pa);
}
// private methods
function &_get_handler($file) {
$ext = strtolower(strrchr($file, '.'));
$ret = false;
if ($ext == '.mp3') {
// mp3
$ret = &$this->_mp3;
if (!$ret) $ret = new _mp3exif();

}
else if ($ext == '.wma')
{ // wma
$ret = &$this->_wma;
if (!$ret) $ret = new _wmaexif();
}
else
{ // unknown
trigger_error('audioexif not supported `' . $ext . '` file.', e_user_warning);
}
return $ret;
}
}

// dbcs => gb2312
function dbcs_gbk($str)
{
// strip the last "\0\0"
$str = substr($str, 0, -2);
return mb_convert_encoding($str, 'gbk', 'ucs-2le');
}

// gb2312 => dbcs
function gbk_dbcs($str)
{
$str = mb_convert_encoding($str, 'ucs-2le', 'gbk');
$str .= "\0\0";
return $str;
}

// file exif
class _audioexif
{
var $fd;
var $head;
var $head_off;
var $head_buf;

// init the file handler
function _file_init($fpath, $write = false)
{
$mode = ($write ? 'rb+' : 'rb');
$this->fd = @fopen($fpath, $mode);
if (!$this->fd)
{
trigger_error('audioexif: `' . $fpath . '` can not be opened with mode `' . $mode . '`', e_user_warning);
return false;
}
$this->head = false;
$this->head_off = 0;
$this->head_buf = '';
return true;
}

// read buffer from the head_buf & move the off pointer
function _read_head_buf($len)
{
if ($len <= 0) return null;
$buf = substr($this->head_buf, $this->head_off, $len);
$this->head_off += strlen($buf);
return $buf;
}

// read one short value
function _read_head_short()
{
$ord1 = ord(substr($this->head_buf, $this->head_off, 1));
$ord2 = ord(substr($this->head_buf, $this->head_off+1, 1));
$this->head_off += 2;
return ($ord1 + ($ord2<<8));
}

// save the file head
function _file_save($head, $olen, $nlen = 0)
{
if ($nlen == 0) $nlen = strlen($head);
if ($nlen == $olen)
{
// shorter
flock($this->fd, lock_ex);
fseek($this->fd, 0, seek_set);
fwrite($this->fd, $head, $nlen);
flock($this->fd, lock_un);
}
else
{
// longer, buffer required
$stat = fstat($this->fd);
$fsize = $stat['size'];

// buf required (4096?) 应该不会 nlen - olen > 4096 吧
$woff = 0;
$roff = $olen;

// read first buffer
flock($this->fd, lock_ex);
fseek($this->fd, $roff, seek_set);
$buf = fread($this->fd, 4096);

// seek to start
fseek($this->fd, $woff, seek_set);
fwrite($this->fd, $head, $nlen);
$woff += $nlen;

// seek to woff & write the data
do
{
$buf2 = $buf;
$roff += 4096;
if ($roff < $fsize)
{
fseek($this->fd, $roff, seek_set);
$buf = fread($this->fd, 4096);
}

// save last buffer
$len2 = strlen($buf2);
fseek($this->fd, $woff, seek_set);
fwrite($this->fd, $buf2, $len2);
$woff += $len2;
}
while ($roff < $fsize);
ftruncate($this->fd, $woff);
flock($this->fd, lock_un);
}
}

// close the file
function _file_deinit()
{
if ($this->fd)
{
fclose($this->fd);
$this->fd = false;
}
}
}

// wma class
class _wmaexif extends _audioexif
{
var $items1 = array('title', 'artist', 'copyright', 'description', 'reserved');
var $items2 = array('year', 'genre', 'albumtitle');

// check file size (length) maybe invalid file
function check_size($file)
{
$ret = false;
if (!$this->_file_init($file)) return true;
if ($this->_init_header())
{
$buf = fread($this->fd, 24);
$tmp = unpack('h32id/vlen/h8unused', $buf);
if ($tmp['id'] == '3626b2758e66cf11a6d900aa0062ce6c')
{
$stat = fstat($this->fd);
$ret = ($stat['size'] == ($this->head['len'] + $tmp['len']));
}
}
$this->_file_deinit();
return $ret;
}

// set info (save the infos)
function set_info($file, $pa)
{
// check the pa
settype($pa, 'array');
if (!$this->_file_init($file, true)) return false;
if (!$this->_init_header())
{
$this->_file_deinit();
return false;
}

// parse the old header & generate the new header
$head_body = '';
$st_found = $ex_found = false;
$head_num = $this->head['num'];
while (($tmp = $this->_get_head_frame()) && ($head_num > 0))
{
$head_num--;
if ($tmp['id'] == '3326b2758e66cf11a6d900aa0062ce6c')
{ // standard info
// 1-4
$st_found = true;
$st_body1 = $st_body2 = '';
$lenx = unpack('v5', $this->_read_head_buf(10));
$tmp['len'] -= 34; // 10 + 24
for ($i = 0; $i < count($this->items1); $i++)
{
$l = $lenx[$i+1];
$k = $this->items1[$i];
$tmp['len'] -= $l;

$data = $this->_read_head_buf($l);
if (isset($pa[$k])) $data = gbk_dbcs($pa[$k]);

$st_body2 .= $data;
$st_body1 .= pack('v', strlen($data));
}
// left length
if ($tmp['len'] > 0) $st_body2 .= $this->_read_head_buf($tmp['len']);

// save to head_body
$head_body .= pack('h32vh8', $tmp['id'], strlen($st_body1 . $st_body2)+24, $tmp['unused']);
$head_body .= $st_body1 . $st_body2;

$st_body2 .= $data;
}

// save to head_body
$head_body .= pack('h32va4', '3326b2758e66cf11a6d900aa0062ce6c', strlen($st_body1 . $st_body2)+24, '');
$head_body .= $st_body1 . $st_body2;
$this->head['num']++;
}
// ex not found?
if (!$ex_found)
{
$inum = 0;
$et_body = '';
foreach ($this->items2 as $k)
{
$nbuf = gbk_dbcs('wm/' . $k);
$vbuf = (isset($pa[$k]) ? gbk_dbcs($pa[$k]) : "");
$et_body .= pack('v', strlen($nbuf)) . $nbuf . pack('vv', 0, strlen($vbuf)) . $vbuf;
$inum++;
}
$head_body .= pack('h32va4v', '40a4d0d207e3d21197f000a0c95ea850', strlen($et_body)+26, '', $inum);
$head_body .= $et_body;
$this->head['num']++;
}

// after save
$new_len = strlen($head_body) + 30;
$old_len = $this->head['len'];
if ($new_len < $old_len)
{
$head_body .= str_repeat("\0", $old_len - $new_len);
$new_len = $old_len;
}
$tmp = $this->head;
$head_buf = pack('h32vvvh4', $tmp['id'], $new_len, $tmp['len2'], $tmp['num'], $tmp['unused']);
$head_buf .= $head_body;
$this->_file_save($head_buf, $old_len, $new_len);

// close the file & return
$this->_file_deinit();
return true;
}

// get info
function get_info($file)
{
$ret = array();
if (!$this->_file_init($file)) return false;
if (!$this->_init_header())
{
$this->_file_deinit();
return false;
}

// get the data from head_buf
$head_num = $this->head['num']; // num of head_frame
while (($tmp = $this->_get_head_frame()) && $head_num > 0)
{
$head_num--;
if ($tmp['id'] == '3326b2758e66cf11a6d900aa0062ce6c')
{ // standard info
$lenx = unpack('v*', $this->_read_head_buf(10));
for ($i = 1; $i <= count($this->items1); $i++)
{
$k = $this->items1[$i-1];
$ret[$k] = dbcs_gbk($this->_read_head_buf($lenx[$i]));
}
}
else if ($tmp['id'] == '40a4d0d207e3d21197f000a0c95ea850')
{ // extended info
$inum = $this->_read_head_short();
$tmp['len'] -= 26;
while ($inum > 0 && $tmp['len'] > 0)
{
// attribute name
$nlen = $this->_read_head_short();
$nbuf = $this->_read_head_buf($nlen);

// the flag & value length
$flag = $this->_read_head_short();
$vlen = $this->_read_head_short();
$vbuf = $this->_read_head_buf($vlen);

// update the xx

$tmp['len'] -= (6 + $nlen + $vlen);
$inum--;

$name = dbcs_gbk($nbuf);
$k = substr($name, 3);
if (in_array($k, $this->items2))
{ // all is string value (refer to falg for other tags)
$ret[$k] = dbcs_gbk($vbuf);
}
}
}

else
{ // skip only
if ($tmp['len'] > 24) $this->head_off += ($tmp['len'] - 24);
}
}
$this->_file_deinit();
return $ret;
}

// get the header?
function _init_header()
{
fseek($this->fd, 0, seek_set);
$buf = fread($this->fd, 30);
if (strlen($buf) != 30) return false;
$tmp = unpack('h32id/vlen/vlen2/vnum/h4unused', $buf);
if ($tmp['id'] != '3026b2758e66cf11a6d900aa0062ce6c')
return false;

$this->head_buf = fread($this->fd, $tmp['len'] - 30);
$this->head = $tmp;
return true;
}

// _get_head_frame()
function _get_head_frame()
{
$buf = $this->_read_head_buf(24);
if (strlen($buf) != 24) return false;
$tmp = unpack('h32id/vlen/h8unused', $buf);
return $tmp;
}
}

// mp3 class (if not idv2 then select idv1)
class _mp3exif extends _audioexif
{
var $head1;
var $genres = array('blues','classic rock','country','dance','disco','funk','grunge','hip-hop','jazz','metal','new age','oldies','other','pop','r&b','rap','reggae','rock','techno','industrial','alternative','ska','death metal','pranks','soundtrack','euro-techno','ambient','trip-hop','vocal','jazz+funk','fusion','trance','classical','instrumental','acid','house','game','sound clip','gospel','noise','alternrock','bass','soul','punk','space','meditative','instrumental pop','instrumental rock','ethnic','gothic','darkwave','techno-industrial','electronic','pop-folk','eurodance','dream','southern rock','comedy','cult','gangsta','top 40','christian rap','pop/funk','jungle','native american','cabaret','new wave','psychadelic','rave','showtunes','trailer','lo-fi','tribal','acid punk','acid jazz','polka','retro','musical','rock & roll','hard rock','unknown');

// mp3 always return true
function check_size($file)
{
return true;
}

// get info
function get_info($file)
{
if (!$this->_file_init($file)) return false;
$ret = false;
if ($this->_init_header())
{
$ret = ($this->head ? $this->_get_v2_info() : $this->_get_v1_info());
$ret['meta'] = $this->_get_meta_info();
}
$this->_file_deinit();
return $ret;
}

// set info
function set_info($file, $pa)
{
if (!$this->_file_init($file, true)) return false;
if ($this->_init_header())
{
// always save v1 info
$this->_set_v1_info($pa);
// set v2 first if need
$this->_set_v2_info($pa);
}
$this->_file_deinit();
return true;
}

// get the header information[v1+v2], call after file_init
function _init_header()
{
$this->head1 = false;
$this->head = false;

// try to get id3v1 first
fseek($this->fd, -128, seek_end);
$buf = fread($this->fd, 128);

if (strlen($buf) == 128 && substr($buf, 0, 3) == 'tag')
{
$tmp = unpack('a3id/a30title/a30artist/a30albumtitle/a4year/a28description/creserved/ctrack/cgenre', $buf);
$this->head1 = $tmp;
}

// try to get id3v2
fseek($this->fd, 0, seek_set);
$buf = fread($this->fd, 10);
if (strlen($buf) == 10 && substr($buf, 0, 3) == 'id3')
{
$tmp = unpack('a3id/cver/crev/cflag/c4size', $buf);
$tmp['size'] = ($tmp['size1']<<21)|($tmp['size2']<<14)|($tmp['size3']<<7)|$tmp['size4'];
unset($tmp['size1'], $tmp['size2'], $tmp['size3'], $tmp['size4']);

$this->head = $tmp;
$this->head_buf = fread($this->fd, $tmp['size']);
}
return ($this->head1 || $this->head);
}

// get v1 info
function _get_v1_info()
{
$ret = array();
$tmpa = array('title', 'artist', 'copyright', 'description', 'year', 'albumtitle');
foreach ($tmpa as $tmp)
{
$ret[$tmp] = $this->head1[$tmp];
if ($pos = strpos($ret[$tmp], "\0"))
$ret[$tmp] = substr($ret[$tmp], 0, $pos);
}

// count the genre, [track]
if ($this->head1['reserved'] == 0) $ret['track'] = $this->head1['track'];
else $ret['description'] .= chr($ret['reserved']) . chr($ret['track']);

// genre_idx
$g = $this->head1['genre'];
if (!isset($this->genres[$g])) $ret['genre'] = 'unknown';
else $ret['genre'] = $this->genres[$g];

// return the value
$ret['id3v1'] = 'yes';
return $ret;
}

// get v2 info
function _get_v2_info()
{
$ret = array();
$items = array( 'tcop'=>'copyright', 'tpe1'=>'artist', 'tit2'=>'title', 'trck'=> 'track',
'tcon'=>'genre', 'comm'=>'description', 'tyer'=>'year', 'talb'=>'albumtitle');
while (true)
{
$buf = $this->_read_head_buf(10);
if (strlen($buf) != 10) break;
$tmp = unpack('a4fid/nsize/nflag', $buf);
if ($tmp['size'] == 0) break;
$tmp['dat'] = $this->_read_head_buf($tmp['size']);

// 0x6000 (11000000 00000000)
if ($tmp['flag'] & 0x6000) continue;

// mapping the data
if ($k = $items[$tmp['fid']])
{ // if first char is "\0", just skip
if (substr($tmp['dat'], 0, 1) == "\0") $tmp['dat'] = substr($tmp['dat'], 1);
$ret[$k] = $tmp['dat'];
}
}

// reset the genre
if ($g = $ret['genre'])
{
if (substr($g,0,1) == '(' && substr($g,-1,1) == ')') $g = substr($g, 1, -1);
if (is_numeric($g))
{
$g = intval($g);
$ret['genre'] = (isset($this->genres[$g]) ? $this->genres[$g] : 'unknown');
}
}

$ret['id3v1'] = 'no';
return $ret;
}
// get meta info of mp3
function _get_meta_info()
{
// seek to the lead buf: 0xff
$off = 0;
if ($this->head) $off = $this->head['size'] + 10;
fseek($this->fd, $off, seek_set);
while (!feof($this->fd))
{
$skip = ord(fread($this->fd, 1));
if ($skip == 0xff) break;
}
if ($skip != 0xff) return false;
$buf = fread($this->fd, 3);
if (strlen($buf) != 3) return false;
$tmp = unpack('c3', $buf);
if (($tmp[1] & 0xf0) != 0xf0) return false;
// get the meta info
$meta = array();
// get mpeg version
$meta['mpeg'] = ($tmp[1] & 0x08 ? 1 : 2);
$meta['layer'] = ($tmp[1] & 0x04) ? (($tmp[1] & 0x02) ? 1 : 2) : (($tmp[1] & 0x02) ? 3 : 0);
$meta['epro'] = ($tmp[1] & 0x01) ? 'no' : 'yes';
// bit rates
$bit_rates = array(
1 => array(
1 => array(0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0),
2 => array(0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,0),
3 => array(0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0)
),
2 => array(
1 => array(0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,0),
2 => array(0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0),
3 => array(0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0)
)
);
$i = $meta['mpeg'];
$j = $meta['layer'];
$k = ($tmp[2]>>4);
$meta['bitrate'] = $bit_rates[$i][$j][$k];
// sample rates <采样率>
$sam_rates = array(1=>array(44100,48000,32000,0), 2=>array(22050,24000,16000,0));
$meta['samrate'] = $sam_rates[$i][$k];
$meta["padding"] = ($tmp[2] & 0x02) ? 'on' : 'off';
$meta["private"] = ($tmp[2] & 0x01) ? 'on' : 'off';
// mode & mode_ext
$k = ($tmp[3]>>6);
$channel_modes = array('stereo', 'joint stereo', 'dual channel', 'single channel');
$meta['mode'] = $channel_modes[$k];
$k = (($tmp[3]>>4) & 0x03);
$extend_modes = array('mpg_md_lr_lr', 'mpg_md_lr_i', 'mpg_md_ms_lr', 'mpg_md_ms_i');
$meta['ext_mode'] = $extend_modes[$k];
$meta['copyright'] = ($tmp[3] & 0x08) ? 'yes' : 'no';
$meta['original'] = ($tmp[3] & 0x04) ? 'yes' : 'no';
$emphasis = array('none', '50/15 microsecs', 'rreserved', 'ccitt j 17');
$k = ($tmp[3] & 0x03);
$meta['emphasis'] = $emphasis[$k];
return $meta;
}
// set v1 info
function _set_v1_info($pa)
{
// id3v1 (simpled)
$off = -128;
if (!($tmp = $this->head1))
{
$off = 0;
$tmp['id'] = 'tag';
$tmp['title'] = $tmp['artist'] = $tmp['albumtitle'] = $tmp['year'] = $tmp['description'] = '';
$tmp['reserved'] = $tmp['track'] = $tmp['genre'] = 0;
}

// basic items
$items = array('title', 'artist', 'copyright', 'description', 'year', 'albumtitle');
foreach ($items as $k)
{
if (isset($pa[$k])) $tmp[$k] = $pa[$k];
}
// genre index
if (isset($pa['genre']))
{
$g = 0;
foreach ($this->genres as $gtmp)
{
if (!strcasecmp($gtmp, $pa['genre']))
break;
$g++;
}
$tmp['genre'] = $g;
}
if (isset($pa['track'])) $tmp['track'] = intval($pa['track']);
// pack the data
$buf = pack('a3a30a30a30a4a28ccc', $tmp['id'], $tmp['title'], $tmp['artist'], $tmp['albumtitle'],
$tmp['year'], $tmp['description'], 0, $tmp['track'], $tmp['genre']);
flock($this->fd, lock_ex);
fseek($this->fd, $off, seek_end);
fwrite($this->fd, $buf, 128);
flock($this->fd, lock_un);
}
// set v2 info
function _set_v2_info($pa)
{
if (!$this->head)
{ // insert id3
return; // 没有就算了
/**
$tmp = array('id'=>'id3','ver'=>3,'rev'=>0,'flag'=>0);
$tmp['size'] = -10; // +10 => 0
$this->head = $tmp;
$this->head_buf = '';
$this->head_off = 0;
**/
}
$items = array( 'tcop'=>'copyright', 'tpe1'=>'artist', 'tit2'=>'title', 'trac'=>'track',
'tcon'=>'genre', 'comm'=>'description', 'tyer'=>'year', 'talb'=>'albumtitle');
$head_body = '';
while (true)
{
$buf = $this->_read_head_buf(10);
if (strlen($buf) != 10) break;
$tmp = unpack('a4fid/nsize/nflag', $buf);
if ($tmp['size'] == 0) break;
$data = $this->_read_head_buf($tmp['size']);
if (($k = $items[$tmp['fid']]) && isset($pa[$k]))
{
// the data should prefix by "\0" [replace]
$data = "\0" . $pa[$k];
unset($pa[$k]);
}
$head_body .= pack('a4nn', $tmp['fid'], strlen($data), $tmp['flag']) . $data;
}
// reverse the items & set the new tags
$items = array_flip($items);
foreach ($pa as $k => $v)
{
if ($fid = $items[$k])
{
$head_body .= pack('a4nn', $fid, strlen($v) + 1, 0) . "\0" . $v;
}
}
// new length
$new_len = strlen($head_body) + 10;
$old_len = $this->head['size'] + 10;
if ($new_len < $old_len)
{
$head_body .= str_repeat("\0", $old_len - $new_len);
$new_len = $old_len;
}
// count the size1,2,3,4, no include the header
// 较为变态的算法... :p (28bytes integer)
$size = array();
$nlen = $new_len - 10;
for ($i = 4; $i > 0; $i--)
{
$size[$i] = ($nlen & 0x7f);
$nlen >>= 7;
}
$tmp = $this->head;
//echo "old_len : $old_len new_len: $new_len\n";
$head_buf = pack('a3ccccccc', $tmp['id'], $tmp['ver'], $tmp['rev'], $tmp['flag'],
$size[1], $size[2], $size[3], $size[4]);
$head_buf .= $head_body;
$this->_file_save($head_buf, $old_len, $new_len);
}

以上所述就是本文的全部内容了,希望大家能够喜欢。