search
HomePHP FrameworkLaravelDetailed explanation of how laravel installs FFmpeg and processes video files

Ubuntu 18.04 Install FFmpeg

1. Download the source code, compile and install

1.1 Download the source code

github address: github.com/PHP-FFMpeg/PHP-FFMpeg

There are three main installations: yasm, sdl1 .2 and sdl2.0

安装 yasmsudo apt-get install yasm
安装sdl1.2sudo apt-get install libsdl1.2-dev
安装 sdl2.0sudo apt-get install libstdl2-devsudo apt-get install libstdl2-dev
If there is an error in the installation of sdl2.0, you can choose the compilation and installation method:

Download the latest version from the official website: www.libsdl.org/download-2.0.php
Unzip Then enter the directory and execute the following commands in sequence:

./configure
make
sudo make install

##1.3 Compile and install ffmpeg Enter the ffmpeg folder and execute the following commands in sequence:


 ./configuremakesudo make install
Insert picture description here1.4 Test whether the installation is successful

ffmpeg -version
ffplay -version

laravel installation

PHP-FFMpeg

Extension

composer require php-ffmpeg/php-ffmpeg
Basic use

1.1. Introduction to the project

The introduction is completed. It needs to formulate two configuration file information for us to use normally, which is the ffmpeg and ffprobe mentioned above
1.2. Global configuration

Add code to

AppServiceProvider.php

<pre class="brush:php;toolbar:false">    public function boot()     {         $this-&gt;registerSingleObject();     }      private function registerSingleObject()     {//       $ffmpeg = FFMpeg::create(array(//           'ffmpeg.binaries'  =&gt; '/usr/local/ffmpeg/ffmpeg',//           'ffprobe.binaries' =&gt; '/usr/local/ffmpeg/ffprobe',//           'timeout'          =&gt; 3600, // The timeout for the underlying process//           'ffmpeg.threads'   =&gt; 12,   // The number of threads that FFMpeg should use//       ));         $this-&gt;app-&gt;singleton('ffmpeg', function ($app) {             return FFMpeg::create([                 'ffmpeg.binaries'  =&gt; '/usr/local/ffmpeg/ffmpeg',                 'ffprobe.binaries' =&gt; '/usr/local/ffmpeg/ffprobe',             ]);         });         $this-&gt;app-&gt;singleton('ffprobe', function ($app) {             return FFProbe::create([                 'ffprobe.binaries' =&gt; '/usr/local/ffmpeg/ffprobe',             ]);         });     }</pre>Use singleton mode to obtain

FFMpeg

and FFProbe objects, where exec('which ffmpeg') is to obtain program location information in order to create a class

The first second of the video is the cover
  • Get the basic information of the video
  • <?php namespace AppHelpers;use FFMpegCoordinateTimeCode;use IlluminateSupportStr;class FFMpegUtil{
    
        // 获取视频信息
        public static function getVideoInfo($streamPath)
        {
            $ffprobe = app(&#39;ffprobe&#39;);
            $stream  = $ffprobe->streams($streamPath)->videos()->first();
            return $stream ? $stream->all() : [];
        }
    
        // 截取
        public static function getCover($streamPath, $fromSecond)
        {
            $ffmpeg   = app('ffmpeg');
            $video    = $ffmpeg->open($streamPath);
            $frame    = $video->frame(TimeCode::fromSeconds($fromSecond)); //提取第几秒的图像
            $fileName = 'video/' . Str::random(12) . '.jpg';
            if (!is_dir(storage_path("video"))) {
                mkdir(storage_path("video"), 0777);
            }
            $frame->save(storage_path($fileName));
            return $fileName;
        }}
public function saveVideotoQiniu($file)
    {
        Auth::loginUsingId(1);
        if ($user = getUser()) {

            // 1.判断是否存在此视频
            $path  = $file->getRealPath();
            $hash  = md5_file($path);
            $video = Video::firstOrNew(['json->hash' => $hash]);
            if ($video->id) {
                $video->touch();
                return $video;
            }

            // 2.保存到 云
            $cdn_path = $this->saveFile($file);
            $db_path  = getPath($cdn_path);

            // 3.获取截图
            $fileName = FFMpegUtil::getCover($path, 1);
            $image    = $this->saveImage(new UploadedFile(storage_path($fileName), 'file.jpg'));

            //4.设置视频信息
            $data     = [];
            $data     = FFMpegUtil::getVideoInfo($path);
            $duration = array_get($data, 'duration');
            $duration = $duration > 0 ? ceil($duration) : $duration;

            $video->path    = $db_path;
            $video->user_id = $user->id;
            $video->setJsonData('width', array_get($data, 'width'));
            $video->setJsonData('height', array_get($data, 'height'));
            $video->duration = $duration;
            $video->setJsonData('cover', $image->path);
            $video->save();
        }
    }

saveImage

in the example is a function that uploads images to the cloud and returns the uploaded image URLFor more laravel technical articles, please visit

laravel tutorial

column!

The above is the detailed content of Detailed explanation of how laravel installs FFmpeg and processes video files. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version