天天看点

ffmpeg获取视频时长(秒数)

/**
 * 是否windows服务器
 *
 * @return boolean
 */
function isWinOs(){

    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') 
    {
        return 1;
    }
    return 0;
}

 /**
 * 注意:此方法在Linux服务器/Windows上有效果 需安装FFmpeg
 * FFmpeg获得视频文件的总长度时间(秒数)
 * @param file 视频文件的地址
 * @param ffmpeg_path ffmpeg的绝对路径 windows服务器 必须 $ffmpeg = 'D:\\items\\ffmpeg\\bin\\ffmpeg.exe';
 */
function getVideoTime($file,$ffmpeg_path=''){

    $duration_in_seconds = 0;
    $vtime = false;
    if(isWinOs()){
        $ffmpeg_path = $ffmpeg_path?$ffmpeg_path:'D:\\tony\\ffmpeg-4.4\\bin\\ffmpeg.exe';
        // $file = 'http://xxx.com/uploads/20210603/a854b660ddbcaea11976252bcda02a8d.mp4';
        // $file = 'C:\\Users\\Administrator\\Desktop\\mp4-mp3\\yin1.mp4';
        // if (!file_exists($file)) {
        //     return ['status'=>0, 'msg'=>'视频文件不存在'];
        // }
        $commond = "{$ffmpeg_path} -i {$file} 2>&1";
        exec($commond, $str_res, $str_r);
        if (is_array($str_res)){
            foreach($str_res as $v){
                if (strpos($v, 'Duration') !== false){
                    $vtime = substr($v, stripos($v , '.') - 8, 8);//' Duration: 00:24:28.14, start: 0.000000, bitrate: 486 kb/s'    
                    break;
                }
            }
        }
    }else{
        $vtime = exec("ffmpeg -i ".$file." 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");//总长度
        // $ctime = date("Y-m-d H:i:s",filectime($file));//创建时间
        // error_log(var_export($vtime,true),3,__FILE__.'-vtime-.log');
    }
    //return $vtime; //格式 00:04:42.28
    if($vtime){
        $duration = explode(":",$vtime);
        if($duration){
            $duration_in_seconds = $duration[0]*3600 + $duration[1]*60+ round($duration[2]);//转化为秒
        }
    }
    return $duration_in_seconds;
}