ffmpeg处理视频获取第一帧截屏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jmlxx/article/details/80524566
<?php
//使用PHP SDK,并且使用自定义配置文件
require app_path().'/include/BaiduBce.phar';
require app_path().'/include/SampleConf.php';
require app_path().'/include/Timer.php';
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Util\Time;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosClient;
use BaiduBce\Services\Bos\CannedAcl;
use BaiduBce\Services\Media\MediaClient;
class UploadController extends BaseController{
    public function __construct(){

    }
    public function postVideoUpload()
    {
        set_time_limit(0);
        $oTime = new Timer();
        $oTime->start();
        $BOS_TEST_CONFIG =
        array(
                'credentials' => array(
                        'ak' => '',
                        'sk' => '',
                ),
                'endpoint' => 'http://bj.bcebos.com',
        );

        //调用配置文件中的参数
//      global $BOS_TEST_CONFIG;
        //新建BosClient
        $client = new BosClient($BOS_TEST_CONFIG);

        $bucketName = 'btp2017/'.date('Ymd', time());
        //Bucket是否存在,若不存在创建Bucket
        $exist = $client->doesBucketExist($bucketName);
        if(!$exist){
            $client->createBucket($bucketName);
        }

        $fileName = $_FILES['upload_file']["tmp_name"];
        $attach_filename = $_FILES['upload_file']['name'];
        $attach_fileext = get_filetype($attach_filename);
        $objectKey = date('YmdHis', time()).rand(1000,9999).'.'.$attach_fileext;

        $response = $client->initiateMultipartUpload($bucketName, $objectKey);
        $uploadId =$response->uploadId;
        //设置分块的开始偏移位置
        $offset = 0;
        $partNumber = 1;
        //设置每块为5MB
        $fileSize = $_FILES['upload_file']['size'];
        $partSize = 5 * 1024 * 1024;
        $length = $partSize;
        $partList = array();
        $bytesLeft = $fileSize;
        $e_tags = array();
        //分块上传
        while ($bytesLeft > 0) {
            $length = ($length > $bytesLeft) ? $bytesLeft : $length;
            $response = $client->uploadPartFromFile($bucketName, $objectKey, $uploadId,  $partNumber, $fileName, $offset, $length);
            array_push($partList, array("partNumber"=>$partNumber, "eTag"=>$response->metadata["etag"]));
            $offset += $length;
            $partNumber++;
            $bytesLeft -= $length;
        }

        $response = $client->completeMultipartUpload($bucketName, $objectKey, $uploadId, $partList);
        $switch=0;
        if($switch==1){
                $MEDIA_TEST_CONFIG =
                array(
                        'credentials' => array(
                                'ak' => '',
                                'sk' => '',
                        ),
                        'endpoint' => 'http://media.bj.baidubce.com',
                );
                //新建MediaClient
                $mediaclient = new MediaClient($MEDIA_TEST_CONFIG);
                $pipelineName = "btp_new_queue";
                $sourceKey = $response->key;

                $strs = strstr($response->key, '.');
                /***********截取缩略图***********/
                $source = array("key" => $response->key);
                //设置可选参数,包括缩略图输出方法及截取规则
                $options = array(
                        "target" => array(
                                "keyPrefix" => str_replace($strs, '', $sourceKey),
                                "widthInPixel" => "600",
                                "heightInPixel"=> "450"
                        ),
                        "capture" => array(
                                "mode" => "auto",
                        ),
                );
                $thumbresponse = $mediaclient->createThumbnailJob($pipelineName, $source, $options);
                /***********截取缩略图***********/

                $str = substr($strs,1);

                if($str == 'mp4'){
                    $sFileUrl = $response->location;
        //          $sThumbUrl = str_replace('2017', 'mct', $response->location);
                    $sThumbUrl = str_replace('mp4', 'jpg', $response->location);
                }else{
                    /**********转码**********/
                    $targetKey = str_replace($str, 'mp4', $sourceKey);
            //      $targetKey = "test00.mp4";
                    $presetName = "bce.video_mp4_1280x720_1728kbps";
                    $mediaresponse = $mediaclient->createSimpleJob($pipelineName, $sourceKey, $targetKey, $presetName);
                    $sJobId = $mediaresponse->jobId;
                    if($sJobId){
        //              $sFileUrl = str_replace('2017', 'mct', $response->location);
                        $sFileUrl = str_replace($sourceKey, $targetKey, $response->location);
                        $sThumbUrl = str_replace('mp4', 'jpg', $sFileUrl);
                    }
                    /***********转码***********/
                }
                //获取视频文件时长
                $responseSecond = $mediaclient->getMediaInfoOfFile("btp2017", $sourceKey);
                $iSecond = $responseSecond->durationInSecond;

                $oTime->stop();

                if($sFileUrl && $sThumbUrl){
                    $time = '视频上传成功,用时'.$oTime->spent().'秒';
                    $json = array('video_url'=>$sFileUrl,'thumb_url'=>$sThumbUrl,'info'=>$time,'second'=>$iSecond);
                    echo json_encode($json);
                    die;
                }else{
                    $time = '上传失败';
                    $json = array('video_url'=>'','info'=>$time);
                    echo json_encode($json);
                    die;
                }
        }else{
            //ffmepeg
            //路径
            //下载视频到服务器
            $aInfo = explode('/',$response->location);
            //文件夹
            $jia = isset($aInfo['4']) ? $aInfo['4'] : date('Ymd');
            $filename =isset($aInfo['5']) ? $aInfo['5'] : $aInfo['4'];
            $sPath = "/upload/bosapi/".$jia.'/';
            //$sRealPath = public_path().$sPath.'/video/';
             $sRealPath = public_path().$sPath;
             if( !file_exists($sRealPath)){
                    mkdirs($sRealPath);
             }
            $bucketName = 'btp2017';
            try
            {
                $res = $client->getObjectAsString($bucketName, $jia.'/'.$filename);
                file_put_contents($sRealPath.$filename,$res);
            }
            catch(Exception $e) {
            }
//        return $sRealPath.$filename;
            //视频格式
            $sourceKey = $response->key;
            $strs = strstr($response->key, '.');
            $str = substr($strs,1);

            require_once APP_ROOT.'/include/ffmpegVideo.class.php';
            $ffmpegVideoInfo = new ffmpegVideoInfo();
            if($str != 'mp4'){
                //转码
                 $sFileNameNew = substr($filename,0,(strpos($filename,'.'))).'.mp4';
                 $sFileUrl = $ffmpegVideoInfo->converToMp4($sRealPath.$filename,$sPath,$sFileNameNew);
            }else{
                $sFileUrl = $sPath.$filename;
            }
             //获取缩略图
             $sThumbName = substr($filename,0,(strpos($filename,'.'))).'.jpg';
             $sThumbUrl = $ffmpegVideoInfo->videoThumb($sRealPath.$filename,$sPath,$sThumbName);
             //获取视频时长
              try
            {
                $aVideoInfo = $ffmpegVideoInfo->video_info($sRealPath.$filename);
                $iSecond  = isset($aVideoInfo['seconds']) ? $aVideoInfo['seconds'] : 0;
            }
            catch(Exception $e) {
                $iSecond = 0;
            }

            $json = array('video_url'=>$sFileUrl,'thumb_url'=>$sThumbUrl,'info'=>'','second'=>$iSecond);
            echo json_encode($json);die;
        }
    }

}

ffmpeg类
<?php 

class ffmpegVideoInfo{
    protected $_kc_ffmpeg_path = ' /usr/local/bin/ffmpeg -i "%s" 2>&1';//ffmpeg路径
    public static $videoArr = array('flv', 'mp4');

   /**
    * 获取视频video信息
    * @param unknown_type $file
    */
    public function video_info($file) {
        ob_start();
        passthru(sprintf($this->_kc_ffmpeg_path, $file));
        $info = ob_get_contents();
        ob_end_clean();
      // 通过使用输出缓冲,获取到ffmpeg所有输出的内容。
       $ret = array();
        // Duration: 01:24:12.73, start: 0.000000, bitrate: 456 kb/s
        if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) {
            $ret['duration'] = $match[1]; // 提取出播放时间
            $da = explode(':', $match[1]); 
            $ret['seconds'] = $da[0] * 3600 + $da[1] * 60 + $da[2]; // 转换为秒
            $ret['start'] = $match[2]; // 开始时间
            $ret['bitrate'] = $match[3]; // bitrate 码率 单位 kb
        }

        // Stream #0.1: Video: rv40, yuv420p, 512x384, 355 kb/s, 12.05 fps, 12 tbr, 1k tbn, 12 tbc
        if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {
            $ret['vcodec'] = $match[1]; // 编码格式
            $ret['vformat'] = $match[2]; // 视频格式 
            $ret['resolution'] = $match[3]; // 分辨率
            $a = explode('x', $match[3]);
            $ret['width'] = isset($a[0]);
            $ret['height'] = isset($a[1]);
        }

        // Stream #0.0: Audio: cook, 44100 Hz, stereo, s16, 96 kb/s
        if (preg_match("/Audio: (\w*), (\d*) Hz/", $info, $match)) {
            $ret['acodec'] = $match[1];       // 音频编码
            $ret['asamplerate'] = $match[2];  // 音频采样频率
        }

        if (isset($ret['seconds']) && isset($ret['start'])) {
            $ret['play_time'] = $ret['seconds'] + $ret['start']; // 实际播放时间
        }

        return $ret;
    }
    /**
     * 获取视频截图
     * @param unknown_type $sVideoPath 视频绝对路径
     * @param unknown_type $sThumbPath  缩略图存储路径,相对路径
     * @param unknown_type $sThumbFileName 缩略图名称
     * @param unknown_type $sTime  截图时间
     */
    public static function videoThumb($sVideoPath,$sThumbPath,$sThumbFileName='',$sTime = '00:00:01'){
        //校验文件是否存在
        if(!self::_checkPath($sVideoPath)){
            return false;
        }
        //校验扩展名
        $extension = self::_getExtension($sVideoPath);
        /*if(!in_array($extension, self::$videoArr)){
            return false;
        }*/

        //$sThumbPath = '/upload/bosapi/img/';
        if (!self::_checkPath(public_path().$sThumbPath)) {
            mkdirs(public_path().$sThumbPath);
        }
        //$sThumbFileName = date('YmdHis').'_'.rand(1000,9999).'.jpg';
        $s = " /usr/local/bin/ffmpeg -ss ".$sTime."  -i ".$sVideoPath." ".public_path().$sThumbPath.$sThumbFileName."  -r 1 -vframes 1 -an -vcodec mjpeg ";
        exec($s);
        if(self::_checkPath(public_path().$sThumbPath.$sThumbFileName)){
            return $sThumbPath.$sThumbFileName;
        }else{
            return false;
        }
    }

    protected static function _checkPath($path = NULL){
        if(empty($path)){
            return FALSE;
        }
        if(file_exists($path)){

            return TRUE;
        }else {
            return FALSE;
        }
    }

    protected static  function _getExtension($file){
        return pathinfo($file, PATHINFO_EXTENSION);
    }

    /**
     * 视频转码
     * @param unknown_type $file 原路径,绝对路径
     * @param unknown_type $targetFilePath  目标路径,相对路径
     * @param unknown_type $targetFileName 目标名称
     */
    public function converToMp4($file,$targetFilePath,$targetFileName){
        if (!$file || !$targetFileName || !self::_checkPath($file) ){
            return false;
        }
         $s = "/usr/local/bin/ffmpeg -i ".$file." ".public_path().$targetFilePath.$targetFileName;
         exec($s);
        if(self::_checkPath(public_path().$targetFilePath.$targetFileName)){
            return $targetFilePath.$targetFileName;
        }else{
            return false;
        }
    }




}

“`

猜你喜欢

转载自blog.csdn.net/jmlxx/article/details/80524566
今日推荐