安裝ffmpeg
在實現這個功能之前, 先需要在系統裡安裝名爲ffmpeg的軟體, 在mac系統裡可以用Homebrew來安裝:
brew install ffmpeg
另外, 因爲需要線上服務器都禁用了passthru這個函數, 需要配置一下php.ini, 將passthru函數的禁用狀態給解禁。
使用php解析流媒體
以下是php解析流媒體文档的代碼:
<?php define('FFMPEG_PATH', 'ffmpeg -i "%s" 2>&1'); function getVideoInfo($file) { $command = sprintf(FFMPEG_PATH, $file); ob_start(); passthru($command); $info = ob_get_contents(); ob_end_clean(); $data = []; 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'] = isset($arr_resolution[1]) ? $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; }
用getVideoInfo這個函數代入一個媒體文档看看返回什麽吧~
echo '<pre>'; $foo = getVideoInfo('xxx.mpg'); print_r($foo);