search
HomeBackend DevelopmentPHP Tutorialphp工具类之【视频变换类】

php工具类之【视频转换类】

?

? ? 在这里简要介绍一下搭建视频网站所需要的软件,这些软件包括ffmpeg、mplayer。它们主要用来负责视频的转码工作,ffmpeg基本上对所有格式的视频文件都可以处理,但是对rmvb和rm格式的视频无法转码,这个时候,就需要通过MPlayer转码工具的协助,完成转码任务。

? ? 如果要在网页上播放,就需要转码。如果采用flash播放器播放视频,这个时候就需要转码出flv格式的视频;如果采用html5或者pad播放,就需要转码出MP4格式的视频。在转码的处理中,我们通常会分别转码出两种视频,分别是高清和流畅视频,方便不同网速的用户观看。

class VideoConvert{	//视频的原始文件	var $src;	//后缀名	var $suffix;	//视频实际类型	var $format;	//视频md5value: 在tester中主要用于生成同级目录下的缩略图的初始位置	var $md5value;	//视频长度	var $ori_length;		//视频信息	var $src_identify = array();	//错误日志	var $err_log = array();	//指令地址	var $system_mencoder = '/usr/bin/mencoder ';	var $system_ffmpeg = '/usr/local/bin/ffmpeg ';	var $system_mplayer = '/usr/bin/mplayer ';	var $system_yamdi = '/usr/local/bin/yamdi ';	var $system_qtfaststart = '/usr/local/bin/qt-faststart ';	function __construct($filePath) {		$this->src = $filePath;		//源文件不存在		if (!file_exists($this->src)) {			print_r("the file[$this->src] not exists.\r\n<br>");		} else {			print_r("the file[$this->src] exists.\r\n<br>");		}	}		function init() {		//截取后缀名		$this->suffix = strtolower(substr($this->src, strrpos($this->src, '.')));		        //读取文件内容的前3个字节,判断真实文件格式		$handle = fopen($this->src, 'r');        $this->format = strtolower(fread($handle, 3));        fclose($handle);				//视频的md5值		$this->md5value = md5_file( $this->src );				//inentify		$this->src_identify =$this->getIdentify($this->src);				//视频长度		$this->ori_length = $this->src_identify['id_length'];		$this->ori_length = empty($this->ori_length)?0:$this->ori_length;	}	function showInfo() {		$this->pr("后缀类型:$this->suffix");		$this->pr("实际类型:$this->format");		$this->pr("md5value:$this->md5value");		$this->pr("ori_length:$this->ori_length");		$this->pr("id_demuxer:".$this->src_identify['id_demuxer']);		$this->pr("id_video_format:".$this->src_identify['id_video_format']);	}	function rmvb2avi($src, $dst, $identify) {		//$cmd = $this->system_mencoder." $src -o ".$src."_ -of avi -oac mp3lame -ovc xvid -xvidencopts bitrate=$datarate";		if($identify['id_video_format'] == 'WMV3') {			$cmd = $this->system_mencoder." $src -o $dst -of avi -oac mp3lame -ovc copy";		} else {			$cmd = $this->system_mencoder." $src -o $dst -of avi -oac mp3lame -ovc xvid -xvidencopts fixed_quant=11";		}		$this->pr($cmd);		$handle = @popen($cmd, 'r');		while (!feof($handle)) {			$line = fgets($handle, 1024);		}		@pclose($handle);		return true;	}		function video2f4v($src, $dst, $datarate) {		$cmd = $this->system_ffmpeg." -i ".$src."  -f flv -acodec libfaac -ab 16k -vcodec libx264 -coder 1 -g 250 -keyint_min 25 -sc_threshold 40 -bf 3 -b_strategy 1 -partitions +parti8x8+parti4x4+partp8x8+partb8x8 -directpred 1 -flags +loop -deblockalpha 0 -deblockbeta 0 -flags2 +fastpskip+wpred-dct8x8 -me_method hex -me_range 16 -subq 6 -trellis 1 -b ".$datarate."k -qcomp 1 -i_qfactor 0.71 -qmin 10 -qmax 51 -qdiff 4 -r 29.97 -y ".$dst;//." 2>&1";		$this->pr($cmd);		$handle = @popen($cmd, 'r');		while(!feof($handle)) {			$line = fgets($handle, 1024);		}		@pclose($handle);		return true;	}		function video2flv($src, $dst) {		$cmd = $this->system_ffmpeg." -i $src -f flv -vcodec flv -ar 22050 -acodec libmp3lame -y $dst";		// 2>&1";		$this->pr($cmd);		$handle = @popen($cmd, 'r');		while(!feof($handle)) {			$line = fgets($handle, 1024);		}		@pclose($handle);		return true;	}		//转换mp4供iphone和ipad看	function video2mp4($src, $dst, $rate) {		file_exists($dst.".mp4")[email&#160;protected]($dst.".mp4"):'';		$cmd = $this->system_ffmpeg." -threads 4 -i ".$src." -r 29.97 -vcodec libx264 -flags +loop -cmp +chroma -deblockalpha 0 -crf 24 -bt ".$rate."k -refs 1 -coder 0 -subq 5 -partitions +parti4x4+parti8x8+partp8x8 -g 250 -keyint_min 25 -level 30 -qmin 10 -qmax 51 -trellis 2 -sc_threshold 40 -i_qfactor 0.71 -acodec libfaac -ab 128k -ar 48000 -f mp4 ".$dst.".mp4";		//2>&1";		$this->pr($cmd);		$handle = @popen($cmd, 'r');		while(!feof($handle)) {			$line = fgets($handle, 1024);		}		@pclose($handle);				$mp4identify = $this->getIdentify($dst.".mp4");		$mp4le = abs($mp4identify['id_length']);		if($mp4le>0) {			$cmd = $this->system_qtfaststart." ".$dst.".mp4 ".$dst.".mp4-new"." 2>&1";			$handle = @popen($cmd, 'r');			while(!feof($handle)) {				$line = fgets($handle, 1024);			}			@pclose($handle);			$mp4identify = $this->getIdentify($dst.".mp4-new");			$mp4le = abs($mp4identify['id_length']);			if ($mp4le>0) {				unlink($dst.".mp4");				rename($dst.".mp4-new",$dst.".mp4");			}		}				return true;	}	/**	 * grabImage 抓图-ok	 * 	 * @param string $src 源文件	 * @param string $dst 目标文件	 * @param int $length 时长	 * @param int $pic_count 截图数量	 * @access public	 * @return void	 */	function grabImage($src, $dst, $length,$pic_count) {		$grabRes = $this->grabImageFfmpeg($src, $dst, $length,$pic_count);        if (@!filesize($dst)) {            return false;        }		return $grabRes;	}	/**	 * grabImageFfmpeg 通过ffmpeg抓图-ok	 * 	 * @param string $src 源文件	 * @param string $dst 目标文件	 * @access public	 * @return void	 */	function grabImageFfmpeg($src, $dst, $length,$pic_count) {		//在视频中间截图		$ss = $length/2;		$cmd = $this->system_ffmpeg ." -y -i $src -vframes 1 -ss $ss -an -vcodec mjpeg -f rawvideo $dst 2>&1";			$fd = @popen($cmd, 'r');		while (!feof($fd)) {			$line = fgets($fd, 1024);		}		@pclose($fd);		$count = $pic_count+1;		if ($length>$count) {			$s = $length/$count;			for ($i=1;$i<$count;$i++) {				$dstpic = $dst.'.'.$i.'.jpg';				$cmd = $this->system_ffmpeg ." -y -i $src -vframes 1 -ss ".($i*$s)." -an -vcodec mjpeg -f rawvideo $dstpic 2>&1";				$fd = @popen($cmd, 'r');				while (!feof($fd)) {					$line = fgets($fd, 1024);				}				fclose($fd);			}		}		return true;	}		/**	* resizeImage从一个已有图片建立一个新的图片-ok	 * @param string $src 源文件	 * @param string $obj 目标文件	 * @param string $width 目标文件宽	 * @param string $height 目标文件高	 * @access public	*/	function resizeImage($src, $obj, $width, $height) {		list($width_orig, $height_orig, $type_orig) = getimagesize($src);		if ($width && ($width_orig < $height_orig)) {			$width = ($height / $height_orig) * $width_orig;		} else {			$height = ($width / $width_orig) * $height_orig;		}		switch($type_orig) {			case 1: 				$image = imagecreatefromgif($src);				break;			case 2: 				$image = imagecreatefromjpeg($src);				break;			case 3: 				$image = imagecreatefrompng($src);				break;			default:				return false;		}		$image_p = imagecreatetruecolor($width, $height);		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);		imagejpeg($image_p, $obj);		return true;	}	/**	 * injectMetaData 向flv文件添加元数据-ok	 * 				以支持播放器的拖放     * 				返回flv时长	 * @param string $file 	 * @access public	 * @return init or false, if failed	 */	function injectMetaData($file) {		$info = array('code'=>false, 'msg'=>'未开始');		//文件是否存在		if (!file_exists($file)) {			$info['msg'] = '文件不存在。';			return $info;		}		$cmd = $this->system_yamdi . " -i $file -o ".$file."_ | grep lasttimestamp";		$fd = @popen($cmd, 'r');        $lasttimestamp = 0;		while (!feof($fd)) {			$line = fgets($fd, 1024);            if (strpos($line, ':')) {                $lasttimestamp = substr($line, strpos($line, ':') + 1);            }		}		pclose($fd);		$l = $this->getIdentify($file.'_');		if ($l['id_length']) {			unlink($file);			rename($file.'_',$file);		}				//Logger::trace(sprintf('lasttimestamp: %s', $lasttimestamp));		//Logger::debug('Inject End');		if ($lasttimestamp == '' || $lasttimestamp == 0){			$lasttimestamp = $this->getIdentify($file);		}		return $lasttimestamp['id_length'];	}	function pr($msg) {		echo "$msg\r\n<br>";	}		/**	 * getIdentify 获取视频信息-ok	 * @access public	 * @return void	 */	function getIdentify($file) {		$identify = array();		if (!is_readable($file)) {			return false;		}		$cmd = $this->system_mplayer . " -msglevel all=0 -identify -vc dummy -endpos 00:00:00 $file 2>&1";		$fd = @popen($cmd, 'r');		while (!feof($fd)) {			$line = fgets($fd);			if (strpos($line, 'ID_') === 0) {				$line = explode('=', $line);				$line[0] = strtolower($line[0]);				$identify[$line[0]] = trim($line[1]);			}		}		@pclose($fd);		//假如mplayer没有获取到视频长度就用ffmpeg再次获取		//视频长度		$return = $identify['id_length'];		if ($return == '' || !is_numeric($return)){			//再次获取						$cmd = $this->system_ffmpeg . " -i $file 2>&1";			$fd = @popen($cmd, 'r');			while (!feof($fd)) {				$line = fgets($fd);				$line = trim($line);				$line = strtolower($line);				if (strpos($line, 'duration:') === 0) {					$line = explode(',', $line);					$line = explode(':', $line[0]);					$identify['id_length'] = abs($line[1])*3600+abs($line[2])*60+abs(((int)$line[3]));					break;				}			}		}		return $identify;	}		function log($key, $value) {	}}

?

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's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use