With the rapid development of the internet, video has become a primary way for people to access information and entertainment. However, video files are often large. To improve file transfer speed and reduce storage space, websites often need to transcode and compress videos. This article will introduce how to use PHP in combination with the FFmpeg tool to achieve video transcoding and compression functionality.
$sourceFile = 'path/to/source/video'; $targetFile = 'path/to/target/video'; $command = "ffmpeg -i $sourceFile -vcodec libx264 -acodec aac -preset slow -crf 22 $targetFile"; exec($command);
In the above code:
$sourceFile is the path to the original video,
$targetFile is the path to the transcoded video,
-vcodec libx264 specifies using the x264 encoder for video encoding,
-acodec aac specifies using the AAC encoder for audio encoding,
-preset slow uses a slower transcoding speed to ensure better video quality,
-crf 22 is the compression parameter for video quality; the lower the value, the higher the video quality.
By adjusting these parameters, you can perform transcoding according to your needs.
$sourceFile = 'path/to/source/video'; $targetFile = 'path/to/compressed/video'; $command = "ffmpeg -i $sourceFile -vcodec libx264 -acodec aac -s 640x480 -b:v 500k $targetFile"; exec($command);
In this code:
$sourceFile is the path to the original video,
$targetFile is the path to the compressed video,
-s 640x480 sets the resolution of the video to 640x480,
-b:v 500k sets the video bitrate to 500 kbps.
By adjusting these parameters, you can flexibly control the degree of compression and the quality of the video.
$sourceFile = 'path/to/source/video'; $targetFile = 'path/to/transcoded/compressed/video'; $command = "ffmpeg -i $sourceFile -vcodec libx264 -acodec aac -preset slow -crf 22 $targetFile"; exec($command, $output, $returnVar); <p>if ($returnVar === 0) {<br> echo 'Video transcoding/compression successful';<br> } else {<br> echo 'Video transcoding/compression failed. Please check the error message: ' . implode("\n", $output);<br> }<br>
In the above code, the third parameter of the exec() function, $returnVar, returns the execution status of the command. A return value of 0 indicates successful execution, while any non-zero value indicates failure. You can use the error messages in $output to help troubleshoot the issue.