찾다
백엔드 개발PHP 튜토리얼php工具类之【视频变换类】

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) {	}}

?

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오Apr 13, 2025 am 12:20 AM

PHP는 현대 웹 개발, 특히 컨텐츠 관리 및 전자 상거래 플랫폼에서 중요합니다. 1) PHP는 Laravel 및 Symfony와 같은 풍부한 생태계와 강력한 프레임 워크 지원을 가지고 있습니다. 2) Opcache 및 Nginx를 통해 성능 최적화를 달성 할 수 있습니다. 3) PHP8.0은 성능을 향상시키기 위해 JIT 컴파일러를 소개합니다. 4) 클라우드 네이티브 애플리케이션은 Docker 및 Kubernetes를 통해 배포되어 유연성과 확장 성을 향상시킵니다.

PHP 대 기타 언어 : 비교PHP 대 기타 언어 : 비교Apr 13, 2025 am 12:19 AM

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP vs. Python : 핵심 기능 및 기능PHP vs. Python : 핵심 기능 및 기능Apr 13, 2025 am 12:16 AM

PHP와 Python은 각각 고유 한 장점이 있으며 다양한 시나리오에 적합합니다. 1.PHP는 웹 개발에 적합하며 내장 웹 서버 및 풍부한 기능 라이브러리를 제공합니다. 2. Python은 간결한 구문과 강력한 표준 라이브러리가있는 데이터 과학 및 기계 학습에 적합합니다. 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

PHP : 웹 개발의 핵심 언어PHP : 웹 개발의 핵심 언어Apr 13, 2025 am 12:08 AM

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 ​​있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

PHP : 많은 웹 사이트의 기초PHP : 많은 웹 사이트의 기초Apr 13, 2025 am 12:07 AM

PHP가 많은 웹 사이트에서 선호되는 기술 스택 인 이유에는 사용 편의성, 강력한 커뮤니티 지원 및 광범위한 사용이 포함됩니다. 1) 배우고 사용하기 쉽고 초보자에게 적합합니다. 2) 거대한 개발자 커뮤니티와 풍부한 자원이 있습니다. 3) WordPress, Drupal 및 기타 플랫폼에서 널리 사용됩니다. 4) 웹 서버와 밀접하게 통합하여 개발 배포를 단순화합니다.

과대 광고 : 오늘 PHP의 역할을 평가합니다과대 광고 : 오늘 PHP의 역할을 평가합니다Apr 12, 2025 am 12:17 AM

PHP는 현대적인 프로그래밍, 특히 웹 개발 분야에서 강력하고 널리 사용되는 도구로 남아 있습니다. 1) PHP는 사용하기 쉽고 데이터베이스와 완벽하게 통합되며 많은 개발자에게 가장 먼저 선택됩니다. 2) 동적 컨텐츠 생성 및 객체 지향 프로그래밍을 지원하여 웹 사이트를 신속하게 작성하고 유지 관리하는 데 적합합니다. 3) 데이터베이스 쿼리를 캐싱하고 최적화함으로써 PHP의 성능을 향상시킬 수 있으며, 광범위한 커뮤니티와 풍부한 생태계는 오늘날의 기술 스택에 여전히 중요합니다.

PHP의 약한 참고 자료는 무엇이며 언제 유용합니까?PHP의 약한 참고 자료는 무엇이며 언제 유용합니까?Apr 12, 2025 am 12:13 AM

PHP에서는 약한 참조가 약한 회의 클래스를 통해 구현되며 쓰레기 수집가가 물체를 되 찾는 것을 방해하지 않습니다. 약한 참조는 캐싱 시스템 및 이벤트 리스너와 같은 시나리오에 적합합니다. 물체의 생존을 보장 할 수 없으며 쓰레기 수집이 지연 될 수 있음에 주목해야합니다.

PHP의 __invoke 마법 방법을 설명하십시오.PHP의 __invoke 마법 방법을 설명하십시오.Apr 12, 2025 am 12:07 AM

\ _ \ _ 호출 메소드를 사용하면 객체를 함수처럼 호출 할 수 있습니다. 1. 객체를 호출 할 수 있도록 메소드를 호출하는 \ _ \ _ 정의하십시오. 2. $ obj (...) 구문을 사용할 때 PHP는 \ _ \ _ invoke 메소드를 실행합니다. 3. 로깅 및 계산기, 코드 유연성 및 가독성 향상과 같은 시나리오에 적합합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)