PHP获取MP3时长类

最近写个上传MP3的功能,为了方便运营的同学操作,需要上传完MP3后自动获取音乐时长,然后自动插入到input里,关于MP3获取时长的类有好几个,试过之后决定采用下面这种方法。

// 调用方法:
$mp3 = new MP3File($filename);
$a = $mp3->getDurationEstimate();
$b = $mp3->getDuration();
$duration = $mp3::formatTime($b);
// 返回的是一个包含时分秒的数组
class MP3File
{
   
   
    protected $filename;
    public function __construct($filename)
    {
   
   
        $this->filename = $filename;
    }

    public static function formatTime($duration) //as hh:mm:ss
    {
   
   
        //return sprintf("%d:%02d", $duration/60, $duration%60);
        $hours = floor($duration / 3600);
        $minutes = floor( ($duration - ($hours * 3600)) / 60);
        $seconds = $duration - ($hours * 3600) - ($minutes * 60);
        // return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
        return array('hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$seconds);
    }

    //Read first mp3 frame only...  use for CBR constant bit rate MP3s
    public function getDurationEstimate()
    {
   
   
        return $this->getDuration($use_cbr_estimate=true);
    }

    //Read entire file, frame by frame... ie: Variable Bit Rate (VBR)
    public function getDuration($use_cbr_estimate=false)
    {
   
   
        $fd = fopen($this->filename, "rb");

        $duration=0;
        $block = fread($fd, 100);
        $offset = $this->skipID3v2Tag($block);
        fseek($fd, $offset, SEEK_SET);
        while (!feof($fd))
        {
            $block = fread($fd, 10);
            if (strlen($block)<10) { break; }
            //looking for 1111 1111 111 (frame synchronization bits)
            else if ($block[0]=="\x
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值