1.本地安裝 FFMpeg,官網下載地址:https://ffmpeg.org/download.html#build-windows
解壓後,把資料夾放到自定義目錄,新增系統變數
2.安裝依賴,composer.json 新增
"php-ffmpeg/php-ffmpeg": "^0.19.0",
3.封裝class類
<?php namespace app\api\controller; use FFMpeg\FFMpeg; use think\facade\Config; use FFMpeg\Coordinate\TimeCode; /** * FFMpeg處理音影片 */ class Media extends Common { /** * 獲取影片時長 單位:秒 * @param string $oriPath * @return string */ public function videoDuration(string $oriPath=''): string { $config = [ 'ffmpeg.binaries' => Config::get('app.app_ffmpeg'), 'ffprobe.binaries' => Config::get('app.app_ffprobe') ]; $ffmpeg = FFMpeg::create($config); $video = $ffmpeg->open($oriPath); $duration = $video->getStreams()->first()->get('duration'); return bcdiv($duration,1,0); } /** * 獲取影片封面圖(影片第一幀) * @param string $oriPath * @return string */ public function videoCoverImage(string $oriPath=''): string { try { $config = [ 'ffmpeg.binaries' => Config::get('app.app_ffmpeg'), 'ffprobe.binaries' => Config::get('app.app_ffprobe') ]; $ffmpeg = FFMpeg::create($config); $video = $ffmpeg->open($oriPath); //獲取影片第一幀 $frame = $video->frame(TimeCode::fromSeconds(1)); $imgDir = $this->imgPath . '/' . date('Ymd'); if(!is_dir('.'.$imgDir)){ mkdir('.'.$imgDir, 0755, true); } //儲存圖片 $imgPath = $imgDir . '/' . buildFileName().'.jpg'; $frame->save('.'.$imgPath); echo $imgPath;die; $cos = new Cos(); $res = $cos->uploadStaticFile($imgPath,'.'.$imgPath); if($res['msg']!='success'){ return ''; } unlink('.'.$imgPath); return $imgPath; }catch (\Exception $e){ return ''; } } /** * 獲取音影片基本資訊 */ public function getVideoInfo($file) { $command = sprintf('F:\work\ffmpeg-7.0.1\bin\ffmpeg -i "%s" 2>&1', $file); //你的ffmpeg路徑 ob_start(); passthru($command); $info = ob_get_contents(); ob_end_clean(); $data = array(); if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) { $data['duration'] = $match[1]; //播放時間 $arr_duration = explode(':', $match[1]); $data['seconds'] = $arr_duration[0] * 3600 + $arr_duration[1] * 60 + $arr_duration[2]; //轉換播放時間為秒數 $data['start'] = $match[2]; //開始時間 $data['bitrate'] = $match[3]; //位元速率(kb) } if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) { $data['vcodec'] = $match[1]; //影片編碼格式 $data['vformat'] = $match[2]; //影片格式 $data['resolution'] = $match[3]; //影片解析度 $arr_resolution = explode('x', $match[3]); $data['width'] = $arr_resolution[0]; @$data['height'] = $arr_resolution[1]; } if (preg_match("/Audio: (\w*), (\d*) Hz/", $info, $match)) { $data['acodec'] = $match[1]; //音訊編碼 $data['asamplerate'] = $match[2]; //音訊取樣頻率 } if (isset($data['seconds']) && isset($data['start'])) { $data['play_time'] = $data['seconds'] + $data['start']; //實際播放時間 } $data['size'] = filesize($file); //檔案大小 return $data; } }
4.本地測試
public function testVideo() { $path = base_path()."/test.mp4"; $media = new Media(); // $img_url = $media->videoCoverImage($path); $video_len = $media->videoDuration($path); // $videoInfo = $media->getVideoInfo($path); dump($video_len . '秒'); }
獲取影片時長: