原理上很簡單,就是使用命令行去調(diào)用ffmpeg,然后分析一下輸出是不是有錯誤。
安裝
首先安裝?symfony/process,主要用于包裝一下,用來代替?exec,?passthru,?shell_exec?and?system?。
composer require symfony/process
composer require symfony/filesystem
要注意 Laravel 10.x 是鎖定 symfony 6.4的,所以無法安裝最新的 7.0 ,但用起來也沒什么問題。
創(chuàng)建服務(wù)
照例創(chuàng)建服務(wù),服務(wù)類:VideoMakerService,接口類:VideoMakerContract,服務(wù)提供類:VideoMakerProvider,快捷名稱:videomaker,F(xiàn)acade類:VideoMaker
參考?保姆級教程:Laravel中添加Service
暫時就提供一個服務(wù),把圖片生成幾秒視頻。
public function imageToBaseVideo(string $imageFile, string $targetFile, float $duration): bool{
// $workingDir=$this->ffmpegTempDir;
$params=[
$this->ffmpegFile,
'-loop', '1',
'-framerate', '30',
'-i', $imageFile,
'-vf', 'scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1',
'-c:v', 'libx264',
'-t', $duration,
'-y',
$targetFile,
];
return ExecHelper::run($params);
}
這里使用了 ExecHelper 來運行,只是對Process做了包裝
class ExecHelper{
public static function run(array $params){
$success=false;
$process = new Process($params);
$code=$process->run(function ($type, $buffer): void {
if (Process::ERR === $type) {
Log::debug('ERR > ', $buffer);
} else {
Log::debug('OUT > ', $buffer);
}
});
$success=$code===0;
return $success;
}
}
創(chuàng)建命令行
命令行類:ProcessVideo
public function handle(VideoMakerContract $videoMakerContract)
{
$imageFile = $this->argument('imageFile');
$targetFile = $this->argument('targetFile');
$duration = $this->option('duration');
// print params
$this->info('imageFile: '.$imageFile.' , targetFile: '.$targetFile.' , duration: '.$duration);
// convert to absolute path
$imageFile=PathHelper::toAbsolutePath($imageFile);
// validate imageFile
if(!file_exists($imageFile)){
$this->error('imageFile not exists');
return;
}
$targetFile=PathHelper::toAbsolutePath($targetFile);
// validate targetFile
if(!file_exists($targetFile)){
$this->error('targetFile not exists');
return;
}
// validate duration
if(!is_numeric($duration)){
$this->error('duration must be numeric');
return;
}
$success=$videoMakerContract->imageToBaseVideo($imageFile, $targetFile, $duration);
$this->info('success: '.$success);
}
參考:保姆級教程:Laravel里如何創(chuàng)建自己的命令行?
這里面用到PathHelper就是簡要地補全一下路徑
class PathHelper{
public static function toAbsolutePath(string $path): string{
return Path::makeAbsolute($path, self::currentPath());
}
public static function currentPath(): string{
return realpath('.');
}
}
準備好圖片
復(fù)制任意一張圖片到 storage/app/tmp/t.jpg
運行命令行
./artisan process:video ./storage/app/tmp/t.jpg ./storage/app/tmp/t.mp4 --duration=5
?文章來源:http://www.zghlxwxcb.cn/news/detail-817616.html
輕松生成 t.mp4?,ffmpeg 的參數(shù)可以參考專欄里其他文章文章來源地址http://www.zghlxwxcb.cn/news/detail-817616.html
到了這里,關(guān)于Laravel 10.x 里如何使用ffmpeg的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!