search
HomeBackend DevelopmentPHP TutorialA PHP class for FFMPEG video conversion

<?php class local_video
{
    public $options;
    public $ffmpeg;
    public $phpcms_path;
    public $backup;
    function __construct($options,$ffmpeg,$backup=true)
    {
        $this->opti
        $this->options = array_filter($options) + $this->options;
        $this->ffmpeg=$ffmpeg;	//ffmpeg路径
        $this->backup=$backup;
    }
    //获取视频信息
    function video_info($file)
    {
        ob_start();
        passthru(sprintf($this->ffmpeg . ' -i "%s" 2>&1', $file));//ffmpeg -i test.avi 2>&1
        $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']      = $a[0];
            $ret['height']     = $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']; // 实际播放时间
        }
        $ret['size'] = filesize($file); // 文件大小
        return $ret;
    }
    function convert()
    {
        $verifyToken = md5('unique_salt' . $this->options['timestamp']);
        if ($verifyToken == $this->options['token'])
        {
            $orgFile  = $this->options['org_path'] . $this->options['org'];
            $setting=' ';
            if(isset($this->options['video_size']))
                $setting=$setting.'-vf scale="'.$this->options['video_size'].'"';
            $mp4      = $this->ffmpeg . ' -i  '  . $orgFile . ' -ss 00:01:02 -vcodec libx264 -strict -2 '.$setting.' ' . $this->options['mp4_path_temp'] . $this->options['org'] . '';	//转换视频
            exec($mp4);
            if(isset($this->options['watermark'])){
            	$watermark=' "'.$this->options['watermark'].'" ';
            	$mp4 = $this->ffmpeg.' -i '.$this->options['mp4_path_temp'] . $this->options['org'] . ''.' -vf '.$watermark.' '.$this->options['mp4_path'] . $this->options['org'] . '';	//增加水印
            	exec($mp4);
            	@unlink($this->options['mp4_path_temp'] . $this->options['org'] . '');
            }
            $duration = $this->video_info($orgFile);
            $seconds  = intval($duration['seconds']);
            $offset   = intval($seconds / 21);	//截图间隔 秒
            $thumbs = explode(',', $this->options['thumb_size']);
            for ($i = 0; $i options['thumb_path'] . $this->options['org'] . '/';
                if (!file_exists($targetPath))
                    @mkdir(rtrim($targetPath, '/'), 0777);
                if ($i == 0)
                {
                    $time     = 1;
                    $name     = $i == 0 ? 'default.jpg' : $i . '.jpg';
                    $img_size = $this->options['main_size'];
                }
                else
                {
	                $time       = $i * $offset;
	                $name       = $i . '.jpg';
	                $img_size   = $thumbs[$i-1];
                }
                $jpg = $this->ffmpeg . ' -i  ' . $orgFile . ' -f  image2  -ss ' . $time . ' -vframes 1  -s ' . $img_size . ' ' . $targetPath . $name;	//截图
                @exec($jpg);
            }
            //复制文件到对应的FTP服务器
            $ftp_server    = pc_base::load_config('ftp_server');
            $remote_server = $_POST['remote_server'];
            $ftp_server    = $ftp_server[$remote_server];
            if($ftp_server['ftp_server'])
                pc_base::ftp_upload($orgFile,
                                $ftp_server['ftp_server'],
                                $ftp_server['ftp_user_name'],
                                $ftp_server['ftp_user_pass']);
            //备份到所有FTP服务器
            if($this->backup){
                $ftp_backup = pc_base::load_config('ftp_backup');
                foreach ($ftp_backup as $v)
                {
                    pc_base::ftp_upload( $orgFile,
                                        $ftp_backup['ftp_server'],
                                        $ftp_backup['ftp_user_name'],
                                        $ftp_backup['ftp_user_pass']);
                }
            }
            $result['url']=$ftp_server['ftp_server']['http_address']. $this->options['mp4_path'] . $this->options['uniqid'] . '.mp4';//记录视频播放地址
            $result['uniqid']=$this->options['uniqid'];
            $result['videoTime'] = $this->video_info($orgFile);
            $result['videoTime'] = $result['videoTime']['seconds'];
            return $result;//返回处理结果
        }
        else
            die('验证失败!');
    }
}
?>

Reference

http://www.fieryrain.com/blog/FFMPEG_VIDEO_TIME

http://keren.iteye.com/blog/1773536

http://www.cnblogs.com/ dwdxdy/p/3240167.html

http://www.cnblogs.com/chen1987lei/archive/2010/12/03/1895242.html

The above introduces a PHP class for FFMPEG video conversion, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools