My recent assignment was to develop an online video editing software similar to Biteable, Moovly etc..Well, I knew I could use PHP-FFmpeg
library that allows me to write PHP script and that can interact with ffmpeg
installed on the system. One of the requirement in the project was to add an audio track to the selected video. The ffmpeg
command-line tool allows me to input multiple files using -i
argument. So I can simply pass both the audio and video files as an argument and the job is done. However, achieving the same using PHP-FFMpeg library was a challenge. In this tutorial, I’ll explain how to allow multiple input files in PHP-FFMpeg library.
Let’s look at the below command where -i
argument is used to pass multiple input files to the ffmpeg
command.
$ffmpeg -i movie.mp4 -i audio.mp3 -codec:a libmp3lame -b:a 128k movie_output.mp4
But to achieve the same in PHP-FFMpeg code is not straight forward. I couldn’t find any relevant documentation that explained the procedure to add multiple input files (-i movie.mp4 -i audio.mp3)
.
How to allow multiple input files in PHP-FFMpeg
After an extensive search, I found a solution on StackOverflow. The solution is to add the second input as a filter. Below is the quick fix of the code:
$audioSource = 'audio.mp3'; $video->addFilter(new SimpleFilter(['-i ', $audioSource]));
Below is the complete code of adding audio track to the video. Make sure the movie.mp4, audio.mp3 and php-ffmpeg are available in the path where this file is located.
<?php require_once 'vendor/autoload.php'; $ffmpeg = FFMpeg\FFMpeg::create(); $format = new FFMpeg\Format\Video\X264(); $format->setAudioCodec("aac"); $videoFile='movie.mp4'; $audioFile='audio.mp3'; $captionStaticFilePath=$_SERVER['DOCUMENT_ROOT'].'/'; $outputFile='movie_output.mp4'; try{ $video = $ffmpeg->open($captionStaticFilePath.$videoFile); $video->addFilter(new FFMpeg\Filters\Audio\SimpleFilter(['-i', $audioFile])); $video->save($format, $captionStaticFilePath.$outputFile); die('done'); }catch(Exception $e){ echo $e->getMessage();die; } ?>
thanks for the article it helped me