Showing posts with label FFMPEG. Show all posts
Showing posts with label FFMPEG. Show all posts

Monday, 9 September 2019

How Azure functions can convert mp4 to mp3 with node using ffmpeg?


Pre-requisite
  1. You have created a function with with name "convert-audio"
  2. You have downloaded and uploaded ffmpeg files (ffmpeg.exe) in "site -> wwwroot-> bin"
  3. You have created a folder with name wav_to_mp3 "site -> wwwroot-> wav_to_mp3"


Source Code
//Download the Required module
const http = require('https');
const fs = require('fs');
const childProcess = require('child_process');
//Define constants
const VIDEO_PATH = 'wav_to_mp3/';
const ffmpegLib='bin/ffmpeg';

module.exports =  async function (context, req) {
    ////////////// params declaration
    let bodyData=req.body;
    let audioFile=bodyData.audio_file;
    let videoFile=bodyData.video_file;
    let extension=bodyData.extension;
    
    if (audioFile && videoFile && extension) {
        if(fs.existsSync(VIDEO_PATH+videoFile)){
            await ffmpegConvertVideoToAudio(VIDEO_PATH+videoFile,VIDEO_PATH+audioFile,extension).then(data=>{
                messageData(200,{success:1,'msg':'',result:{audio_file:data.filename}});
           });            
        }else{
            messageData(200,{success:0,msg:"video_file does not exist",'result':{}});
        }

                   
    } else {
        messageData(200,{success:0,msg:"Parameter missing (audio_file OR video_file OR extension)",'result':{}});
    }
    
    //for print the message
    function messageData(statusCode,message){
        context.res = {
            status: statusCode,
            body: message,
            headers: {
                'Content-Type': 'application/json'
            }
        };   
         context.done();
    } 
    
};



///////////////////////////// Other Functions ////////////////////////////////////
function ffmpegConvertVideoToAudio(sourcefile, destinationFile, extension) {
    return new Promise(function(resolve, reject) {
        let result={success:0,'msg':'',filename:destinationFile};
        console.log('ffmpegConvertVideoToAudio called '+destinationFile);
          var args = [
              '-i', sourcefile,
              '-f', extension, destinationFile
          ];
          var proc = childProcess.spawnSync(ffmpegLib, args);   
            result.success=1
            resolve(result);   
    });

}    
///////////////////////////// Other Functions ////////////////////////////////////


URL: https://function-name.azurewebsites.net/api/convert-audio
Method: POST
Request: {"video_file":"0_20190821064650782.mp4","audio_file":"arun.mp3","extension":"mp3"} Response:
{
    "success": 1,
    "msg": "",
    "result": {
        "audio_file": "wav_to_mp3/arun.mp3"
    }
}



URL:
https://function-name.azurewebsites.net/api/convert-audio
Method: POST
Request: {"video_file":"0_20190821064650782.mp4","audio_file":"arun.flac","extension":"flac"} Response:
{
    "success": 1,
    "msg": "",
    "result": {
        "audio_file": "wav_to_mp3/arun.flac"
    }
}

Friday, 6 September 2019

Download the media files with node in Azure serverless

Download the media files with node in Azure serverless

Pre-requisite for Node in Azure Serverless 

  1. You have created a function with with name "download-files"
  2. You have downloaded ffmpeg files (ffmpeg.exe) in "site -> wwwroot-> bin"
  3. You have created a folder with name wav_to_mp3 "site -> wwwroot-> wav_to_mp3"


Source Code

//Download the Required module
const http = require('https');
const fs = require('fs');
//const childProcess = require('child_process');
const path = require('path');

//Define constants
const VIDEO_PATH = 'wav_to_mp3/';
const ffmpegLib='bin/ffmpeg';

module.exports =  function (context, req) {
    ////////////// params declaration
    let bodyData=req.body;
    let tourStreamName=bodyData.tour_stream_name;
    let videoUrls=bodyData.url;
    
    let filename='';
    let filenameSuccessLog={};
    let completedCounter=0;
    if (tourStreamName && videoUrls.length>0) {
        ////////////////////// ALL VIDEOS DOWNLOAD ////////////////////////////
        //const forLoop = async _ => {
         videoUrls.forEach(async (url) => {
              filename=path.basename(url); 
             // let videoDownload=VIDEO_PATH+filename;
                //full video url, filename, force download
                downloadFileAsync(url,filename,0).then(data=>{  
                   filenameSuccessLog[data.filename]=data.success;
                   completedCounter++;
                   if(videoUrls.length==completedCounter){
                       messageData(200,{success:1,'msg':'',result:filenameSuccessLog});
                   }                    
               }); 
          })
        //}    
         //forLoop();
        ////////////////////// ALL VIDEOS DOWNLOAD ////////////////////////////

    } else {
        messageData(200,{success:0,msg:"Parameter missing (tour_stream_name OR url)",'result':{}});
    }
    
    
    
    //for print the message
    function messageData(statusCode,message){
        context.res = {
            status: statusCode,
            body: message,
            headers: {
                'Content-Type': 'application/json'
            }
        };   
         context.done();
               
    } 
    
};



///////////////////////////// Other Functions ////////////////////////////////////
/**
 * @url: url of video
 * @destination: file with name download in wav_to_mp3
 * @forcedownload: 1 means download again even
 */
async function downloadFileAsync(url, destination,forcedownload) {
    return new Promise(function(resolve, reject) {
        let result={success:0,'msg':'',filename:destination};
        if (fs.existsSync(VIDEO_PATH+destination) && forcedownload==0) {
            result.success=1
            resolve(result);            
        }else{
            const file = fs.createWriteStream(VIDEO_PATH+destination);
            const request = http.get(url, (res) => {
              res.pipe(file);
            });
            request.once('error', (error) => 
              {
                  result.msg=error;
                  reject(result);
              }
            );
            file.once('finish', () => 
              {
                result.success=1
                resolve(result);
              }
            );             
        }
       
        
    })
}

///////////////////////////// Other Functions ////////////////////////////////////

URL: https://function-name.azurewebsites.net/api/download-files
Method: POST
Request:
{"tour_stream_name":"arun","url":["https://example.com/video/0_20190821064650782.mp4","https://example.com/video/tq_33038dev-GM-ma9kW-1106-26079.mp4"]}
Response:
{
    "success": 1,
    "msg": "",
    "result": {
        "tq_33038dev-GM-ma9kW-1106-26079.mp4": 1,
        "0_20190821064650782.mp4": 1
    }
}

Install FFMPEG in Azure Serverless Architecture

Install FFMPEG in Azure Serverless Architecture

Create "Function" in "Function App" in Azure (If you have not created)

https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function


Install FFMPEG in Azure Server

  1. Now Go to Function App, and Click on the your "Function App"
  2. Click on "Platform Features" then click on "Advance tools (Kudu)" like blow
  3. In Kudu, select CMD from the Debug console menu.
  4. Now, you can navigate to the folder by click on site -> wwwroot.

  5. Create a folder with bin,here we will put the ffmpeg library.
  6. a. Go to the https://ffmpeg.zeranoe.com/builds/ (for FFMPEG)
    b. Download the build as per Architecture.
    c. Unzip the downloaded content.
    d. Now copy the ffmpeg.exe, ffplay.exe and ffprobe.exe (from bin folder in downloaded).
    e. Copy these three files in site -> wwwroot-> bin folder.
  7. Create a folder with wav_to_mp3,here we will store the media like photo, videos etc.
  8. Here you can run the ffmpeg command such ffmpeg -version



Monday, 31 December 2018

17 FFmpeg Commands For Beginners

17 FFmpeg Commands For Beginners

#1 Getting audio/video file information
ffmpeg -i video.mp4

(use -hide_banner flag to hide information such as version, configuration details, copyright notice, build and library options etc.)


#2 Converting video files into AVI
ffmpeg -i video.mp4 video.avi

(use -qscale 0 to preserve the quality of your source video file)


#3 understand comman Abbr
-i filename (i=Input)
-vn  Indicates that we have disabled video recording in the output file.
-ar  Set the audio frequency of the output file. The common values used are 22050, 44100, 48000 Hz.
-ac  Set the number of audio channels.
-ab  Indicates the audio bitrate.
-f  Output file format. In our case, it’s mp3 format.
-b:v 64k (-b:v video bitrate)
-r 24 (change the frame rate)
-vf video filter (vf video filter)
-af audio filter (af audio filter)
-an file name (No audio)
-sn file name (No sub-title)
-dn file name (No data-stream)



#4 Change resolution of video files
ffmpeg -i input.mp4 -filter:v scale=1280:720 -c:a copy output.mp4



#5 Compressing video files
ffmpeg -i input.mp4 -vf scale=1280:-1 -c:v libx264 -preset veryslow -crf 24 output.mp4



#6 Compressing Audio files
ffmpeg -i input.mp3 -ab 128 output.mp3

96kbps
112kbps
128kbps
160kbps
192kbps
256kbps
320kbps


#7 Removing audio stream from a media file
ffmpeg -i input.mp4 -an output.mp4



#8 Removing video stream from a media file
ffmpeg -i input.mp4 -vn output.mp3



#9 Cropping videos
ffmpeg -i input.mp4 -croptop 100 -cropbottom 100 -cropleft 300 -cropright 300 output.mp4



#12 Set the aspect ratio to video
ffmpeg -i input.mp4 -aspect 16:9 output.mp4



#13 Trim a media file using start and stop times
ffmpeg -i input.mp4 -ss 00:00:50 -codec copy -t 50 output.mp4



#14 Changing resolution and Reencoding
ffmpeg -i 1.mp4 -vf scale=1280:720 -acodec aac -vcodec libx264   NewFile.mp4 -hide_banner



#15 Joining multiple video parts into one
ffmpeg -f concat -i join.txt -c copy output.mp4

(join.txt will have path of all videos)


#16 Add subtitles to a video file
fmpeg -i input.mp4 -i subtitle_file.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset veryfast output.mp4



#17 Increase video playback speed
ffmpeg -i inputvideo.mp4 -vf "setpts=0.5*PTS" outputvideo.mp4





Question: How to execute ssh command in PHP and get the results?
exec("ls",$o);
print_r($o);




Monday, 5 November 2018

How to change the video resolution from 1280X720 to 600X400


Question: Download the php-ffmpeg library (If not downloaded)?
composer require php-ffmpeg/php-ffmpeg




Question: How to change the video resolution from 1280 X 720 to 600 X 400?
    //load the library
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $ffmpeg = FFMpeg\FFMpeg::create();

    //format of new video
    $format = new FFMpeg\Format\Video\X264();
    $format->setAudioCodec("aac");           

    //path of folder where video exist
    $videoFolderPath='folder';

    //change the resolution
    $width=600;
    $height=400;


    //load the video in ffmpeg
    $videoObj = $ffmpeg->open($videoFolderPath.'/input_video.mp4');
    //filter the video with height/width
    $videoObj->filters()->resize(new FFMpeg\Coordinate\Dimension($width, $height), FFMpeg\Filters\Video\ResizeFilter::RESIZEMODE_INSET, true);
    //save the video
    $videoObj->save($format, $videoFolderPath.'/output_video.mp4');   



Wednesday, 24 October 2018

How to add filters (transition) between two videos using php-ffmpeg?

How to add filters (transition) between two videos using php-ffmpeg?

Question: What are the different filters available?
  1. alphaextract: Extract the alpha component from the input as a grayscale video.
  2. alphamerge: Add or replace the alpha component of the primary input with the grayscale value of a second input
    movie=in_alpha.mkv [alpha]; [in][alpha] alphamerge [out]
  3. amplify: Amplify differences between current pixel and pixels of adjacent frames in same pixel location.
  4. atadenoise: Adaptive Temporal Averaging Denoiser to the video input.
  5. avgblur: Apply average blur filter.
  6. bbox: Compute the bounding box for the non-black pixels in the input frame luminance plane.
  7. bitplanenoise: Show and measure bit plane noise.
  8. blackdetect: Detect video intervals that are (almost) completely black.
    blackdetect=d=2:pix_th=0.00



Question: Give few examples?
Apply transition from bottom layer to top layer in first 10 seconds
blend=all_expr='A*(if(gte(T,10),1,T/10))+B*(1-(if(gte(T,10),1,T/10)))'


Apply uncover left effect:
blend=all_expr='if(gte(N*SW+X,W),A,B)'


Apply uncover down effect:
blend=all_expr='if(gte(Y-N*SH,0),A,B)'


Display differences between the current and the previous frame:
tblend=all_mode=grainextract





Question: How to add video filter (transition) on videos with PHP-FFMPEG?
  1. You must have installed PHP-FFMPEG
  2. php composer.phar require php-ffmpeg/php-ffmpeg
    If not, you can check https://www.web-technology-experts-notes.in/2017/10/how-to-install-ffmpeg-in-wamp-server-in-windows7.html

  • Open File Path: \vendor\php-ffmpeg\php-ffmpeg\src\FFMpeg\Media\Concat.php
  • Add following function in Concat.php
     public function saveFromDifferentCodecsTransition(FormatInterface $format, $outputPathfile,$transition=array())
        {
            /**
             * @see https://ffmpeg.org/ffmpeg-formats.html#concat
             * @see https://trac.ffmpeg.org/wiki/Concatenate
             */
    
            // Check the validity of the parameter
            if(!is_array($this->sources) || (count($this->sources) == 0)) {
                throw new InvalidArgumentException('The list of videos is not a valid array.');
            }
    
            // Create the commands variable
            $commands = array();
    
            // Prepare the parameters
            $nbSources = 0;
            $files = array();
    
            // For each source, check if this is a legit file
            // and prepare the parameters
            foreach ($this->sources as $videoPath) {
                $files[] = '-i';
                $files[] = $videoPath;
                $nbSources++;
            }
    
            $commands = array_merge($commands, $files);
    
            // Set the parameters of the request
            $commands[] = '-filter_complex';
    
            $complex_filter = '';
            //$transition =array('transition_effect'=>'fade_out','transition_length'=>1.2);
            
            //No transistion
            if(empty($transition) || @$transition['transition_effect']=='none' || $nbSources==1){
                for($i=0; $i<$nbSources; $i++) {
                    $complex_filter .= '['.$i.':v:0] ['.$i.':a:0] ';
                }   
                
            }else{ //Transition with Fade in/Fade out
                if($transition['transition_effect']=='fade_in'){
                    for($i=0; $i<$nbSources; $i++) {
                        if($i == 0){
                            $complex_filter .='['.$i.':v]setpts=PTS-STARTPTS[v'.$i.'];';            
                        }else{
    
            
                            $complex_filter .='['.$i.':v]fade=type=in:duration='.$transition['transition_length'].',setpts=PTS-STARTPTS[v'.$i.'];';            
                        }
                    }
                }else if($transition['transition_effect']=='fade_out'){
                    for($i=0; $i<$nbSources; $i++) {
                        if($i == ($nbSources-1)){
                            $complex_filter .='['.$i.':v]setpts=PTS-STARTPTS[v'.$i.'];';            
                        }else{
                            $startTime=0;
                            /* Get duration  of video*/
                               try{
                                    $sourceFile = $this->sources[$i];
                                    $ffprobe    = \FFMpeg\FFProbe::create();
                                    $duration=
                                            $ffprobe->streams($sourceFile)
                                            ->videos()                   
                                            ->first()                  
                                            ->get('duration');  
                                    $startTime=$duration-$transition['transition_length'];
                               }catch(Exception $e){
                                   $transition['transition_length']=0;
                               }
                            /* Get duration  of video*/
                            $complex_filter .='['.$i.':v]fade=type=out:start_time='.$startTime.',setpts=PTS-STARTPTS[v'.$i.'];';            
                        }
                    }
                }
                    for($i=0; $i<$nbSources; $i++) {
                        $complex_filter .= '[v'.$i.']['.$i.':a]';
                    }             
                
            }
            
            $complex_filter .= 'concat=n='.$nbSources.':v=1:a=1 [v] [a]';
    
            $commands[] = $complex_filter;
            $commands[] = '-map';
            $commands[] = '[v]';
            $commands[] = '-map';
            $commands[] = '[a]';
    
            // Prepare the filters
            $filters = clone $this->filters;
            $filters->add(new SimpleFilter($format->getExtraParams(), 10));
    
            if ($this->driver->getConfiguration()->has('ffmpeg.threads')) {
                $filters->add(new SimpleFilter(array('-threads', $this->driver->getConfiguration()->get('ffmpeg.threads'))));
            }
            if ($format instanceof VideoInterface) {
                if (null !== $format->getVideoCodec()) {
                    $filters->add(new SimpleFilter(array('-vcodec', $format->getVideoCodec())));
                }
            }
            if ($format instanceof AudioInterface) {
                if (null !== $format->getAudioCodec()) {
                    $filters->add(new SimpleFilter(array('-acodec', $format->getAudioCodec())));
                }
            }
    
            // Add the filters
            foreach ($this->filters as $filter) {
                $commands = array_merge($commands, $filter->apply($this));
            }
    
            if ($format instanceof AudioInterface) {
                if (null !== $format->getAudioKiloBitrate()) {
                    $commands[] = '-b:a';
                    $commands[] = $format->getAudioKiloBitrate() . 'k';
                }
                if (null !== $format->getAudioChannels()) {
                    $commands[] = '-ac';
                    $commands[] = $format->getAudioChannels();
                }
            }
    
            // If the user passed some additional parameters
            if ($format instanceof VideoInterface) {
                if (null !== $format->getAdditionalParameters()) {
                    foreach ($format->getAdditionalParameters() as $additionalParameter) {
                        $commands[] = $additionalParameter;
                    }
                }
            }
    
            // Set the output file in the command
            $commands[] = $outputPathfile;
    
            $failure = null;
    
            try {
                $this->driver->command($commands);
            } catch (ExecutionFailureException $e) {
                throw new RuntimeException('Encoding failed', $e->getCode(), $e);
            }
    
            return $this;
        }



  • Question: How to call above function (used for scale in/scale out) with number of seconds?
    require_once 'ffmpeglib/vendor/autoload.php';
    $ffmpeg = FFMpeg\FFMpeg::create();
    $format = new FFMpeg\Format\Video\X264();
    $format->setAudioCodec("aac");  
    $newFileName='output_video.mp4';
    $captionStaticFilePath=$_SERVER['DOCUMENT_ROOT'].'/myvideos/';
    $videoFiles=array($captionStaticFilePath.'myvideo.mp4',$captionStaticFilePath.'myvideo1.mp4',$captionStaticFilePath.'myvideo2.mp4');
    
    /////////////// Debug ////////////////////////////
    $ffmpeg->getFFMpegDriver()->listen(new \Alchemy\BinaryDriver\Listeners\DebugListener());
    $ffmpeg->getFFMpegDriver()->on('debug', function ($message) {
       echo $message."
    ";
    });
    /////////////// Debug ////////////////////////////    
    $transition=array(
        'transition_effect'=>'fade_in', //fade_in,fade_out, black
        'transition_length'=>4 //number of seconds
    ); 
    try{
    $video = $ffmpeg->open($videoFiles[0])                        
        ->concat($videoFiles)
        ->saveFromDifferentCodecsTransition(new FFMpeg\Format\Video\X264,$captionStaticFilePath.$newFileName,$transition); 
    }catch(Exception $e){
    echo $e->getMessage();
     } 
    



    How to add formated text on video using php-ffmpeg?

    How to add formated text on video using php-ffmpeg?

    Question: What is drawtext on video?
    Adding the single line text/multiple line text over the video.



    Question: Can we change the font-size of text?
    Yes, we can change the color, size, font family etc of text in videos.



    Question: How to add text on videos?
    ffmpeg -i myvideo.mp4 -vf drawtext="fontfile=OpenSans-Bold.ttf: text=this is text on videos: fontcolor=white: fontsize=120: box=1: boxcolor=black@0.5: boxborderw=5: x=(w-text_w)/2: y=(h-text_h)/2" -codec:a copy output_video.mp4
    

    Note: OpenSans-Bold.ttf file must available (with parallel to video i.e myvideo.mp4)



    Question: How to multiple line text on videos?
    ffmpeg -i myvideo.mp4 -vf "[in]drawtext=fontfile=OpenSans-Bold.ttf: text=Arun kumar: fontcolor=white: fontsize=20: box=1: boxcolor=black@0.5: boxborderw=5: x=100: y=100 drawtext=fontfile=OpenSans-Bold.ttf: text='Kuldeep ': fontcolor=white: fontsize=20: box=1: boxcolor=black@0.5: boxborderw=5: x=100: y=400[output]" -codec:a copy output_video.mp4
    

    Note: OpenSans-Bold.ttf file must available (with parallel to video i.e myvideo.mp4)




    Question: How to add text in video with PHP?
    1. You must have installed PHP-FFMPEG
      php composer.phar require php-ffmpeg/php-ffmpeg
      If not, you can check https://www.web-technology-experts-notes.in/2017/10/how-to-install-ffmpeg-in-wamp-server-in-windows7.html
    2. To achieve this, you need to use the ffmpeg filters.
    3. require_once 'ffmpeglib/vendor/autoload.php';
      $ffmpeg = FFMpeg\FFMpeg::create();
      $format = new FFMpeg\Format\Video\X264();
       $format->setAudioCodec("aac");  
      $videoFile='myvideo.mp4';
      $captionStaticFilePath='';//directory path
      $captionStaticFilePath=$_SERVER['DOCUMENT_ROOT'].'/video/';
      
      /////////////// Debug ////////////////////////////
      /*$ffmpeg->getFFMpegDriver()->listen(new \Alchemy\BinaryDriver\Listeners\DebugListener());
      $ffmpeg->getFFMpegDriver()->on('debug', function ($message) {
          echo $message;
      });*/
      /////////////// Debug ////////////////////////////                
      
      /* Filter the text correctly*/ 
      $captionJSON=json_decode('["text=This is caption text: fontfile=OpenSans-Regular.ttf: x=384: y=10: fontcolor=#ffffff: fontsize=24px","text=This is clip 2 - Samik das: fontfile=OpenSans-Bold.ttf: x=404.08331298828125: y=34.91668701171875: fontcolor=#ffffff: fontsize=24px: fonttype=bold"]');
      $captionArray=array();
      if(!empty($captionJSON) && !empty($captionJSON)){
          foreach($captionJSON as $caption){
              //String to array
              $caption=str_replace(':', '&', $caption);
              parse_str($caption, $output);
              //pr($output);die;
      
              unset($output['fonttype']);
              $output['fontsize']=str_replace('px','',$output['fontsize']);
              $output['fontfile']=$captionStaticFilePath.$output['fontfile'];
      
              $output['x'] = (int)$output['x'];
              $output['y'] = (int)$output['y'];
      
              //Array to string
              $outputStr='';
              $counter=0;
              foreach($output as $i=>$v){
                  if($counter){
                      $outputStr.= ': ';
                  }
                  $outputStr.= $i.'='.$v;
                  $counter++;
              }
              //Update to array                            
              $captionArray[]=$outputStr;
          }
      }
      /* Filter the text correctly*/ 
      
      
      try{
          $video = $ffmpeg->open($captionStaticFilePath.$videoFile);
          $command='';
          if(!empty($captionArray)){
              $command='[in]';
              foreach($captionArray as $index=>$captionComand){
                  if($index>0){
                      $command= $command.',';
                  }
                  $command= $command.'drawtext='.$captionComand;
              }
              $command.='[out]';
      
      
          }
      
          //nOW execute the command
          $video->filters()->custom($command);
          $captionFile='caption_'.$videoFile;
          //Save the video with caption
          $video->save($format, $captionStaticFilePath.$captionFile);
          die('done');
      }catch(Exception $e){
          echo $e->getMessage();die;
      }



    Question: How to add debugging in php-ffmpeg?
    Just add below code after the initialize the ffmpeg object.

    $ffmpeg->getFFMpegDriver()->listen(new \Alchemy\BinaryDriver\Listeners\DebugListener());
    $ffmpeg->getFFMpegDriver()->on('debug', function ($message) {
        echo $message;
    });



    Question: Share Few useful urls for drawtext?
    https://www.ffmpeg.org/ffmpeg-all.html#fade
    https://ffmpeg.org/ffmpeg-filters.html


    Friday, 6 July 2018

    How to convert mp4 to mp3 and wav using PHP FFMPEG

    How to convert mp4 to mp3 and wav using PHP FFMPEG


    Question: Download the php-ffmpeg library (If not downloaded)?
    composer require php-ffmpeg/php-ffmpeg
    


    Question: How to convert Mp4 to wav using php-ffmpeg?
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $ffmpeg = FFMpeg\FFMpeg::create();
    $format = new FFMpeg\Format\Audio\Wav();        
    $videoFolderPath='folder';
    
    $audioObj = $ffmpeg->open($videoFolderPath.'/myfile.mp4');    
    $audioObj->save($format, $videoFolderPath.'/myfile.wav');




    Question: How to convert Mp4 to mp3 using php-ffmpeg?
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $ffmpeg = FFMpeg\FFMpeg::create();
    $mp3Format = new FFMpeg\Format\Audio\Mp3(); 
    $videoFolderPath='folder';
    
    
    $audioObj = $ffmpeg->open($videoFolderPath.'/myfile.mp4');    
    $audioObj->save($mp3Format, $videoFolderPath.'/myfile.mp3');



    Thursday, 22 February 2018

    FFMPEG commands - Most common commands

    FFMPEG commands - Most common commands used

    Question: How to combine two mp4 video files?
    ffmpeg -i video1.mp4 -i video2.mp4  -filter_complex concat=n=2:v=1:a=1 -f mp4 -y finalvideo.mp4



    Question: How to combine three mp4 video files?
    ffmpeg -i video1.mp4 -i video2.mp4   -i video3.mp4 -filter_complex concat=n=2:v=1:a=1 -f mp4 -y finalvideo.mp4



    Question: How to combine four mp4 video files?
    ffmpeg -i video1.mp4 -i video2.mp4   -i video3.mp4 -filter_complex concat=n=2:v=1:a=1 -f mp4 -y finalvideo.mp4



    Question: How to combine two video file (and disable video)?
    ffmpeg -i video1.mp4 -i video2.mp4  -filter_complex concat=n=2:v=1:a=1 -f mp4 -vn -y finalvideo.mp4



    Question: How to combine two video file (and disable audio)?
    ffmpeg -i video1.mp4 -i video2.mp4  -filter_complex concat=n=2:v=1:a=1 -f mp4 -an -y finalvideo.mp4



    Question: What are the different -filter_complex options used in ffmpeg?
    concat means use the media concatenate.
    n means total count of input files.
    v means has video? use 0 = no video, 1 = contains video.
    a means has audio? use 0 = no audio, 1 = contain audio.
    -f means force set file format (to see all supported formats, use ffmpeg -formats)
    -vn means disable video 
    -an means disable audio 
    -y means overwrite output files
    



    Question: How to trim first 10 seconds from the audio using ffmpeg?
    ffmpeg -i input_aac.mp4 -ss 10  -acodec copy output_aac.mp4



    Question: How to capture the audio between 10 to 30 audio (20 seconds audio)?
    ffmpeg -ss 10 -t 20 -i file.mp3 -y output.mp3

    -ss 10 - Start at 0 seconds
    -t 20 - Capture 20 seconds (from 0, so 0:10 - 0:30).
    -y : force output file to overwrite.
    



    Question: How to the rescaling the video with specified size 320:240?
    ffmpeg -i input.mp4 -vf scale=320:240 output.mp4



    Question: How to the rescaling the image with specified size 320:240?
    ffmpeg -i input.jpg -vf scale=320:240 output_320x240.jpg



    Question: How to the rescaling the image with specified width size 320 with keeping the Aspect Ratio?
    ffmpeg -i input.jpg -vf scale=320:-1 output_320xauto.jpg



    Tuesday, 20 February 2018

    php FFMpeg extract images from videos

    php FFMpeg extract images from videos in every 10 or nth seconds

    Question: From where download the PHP FFMpeg library?
    Install the php FFMpeg with composer.
    composer require php-ffmpeg/php-ffmpeg



    Question: Check php FFMpeg installed properly or not?
    require 'vendor/autoload.php';
    $ffmpeg = FFMpeg\FFMpeg::create();
    print_r($ffmpeg);
    

    If it will print the object means FFMpeg is proper configure.


    Question: How to extract image from video?
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $folderPath='convert/';
    
    #Create the required Object
    $ffmpeg = FFMpeg\FFMpeg::create();
    $video = $ffmpeg->open($folderPath.'video.mp4');
    
    #extra the image at 10 seconds
    $video
        ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
        ->save('frame_10.jpg');


    #extra the image at 20 seconds
    $video
        ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(20))
        ->save('frame_20.jpg');


    #extra the image at 30 seconds
    $video
        ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(30))
        ->save('frame_30.jpg');
    



    Question: How to extract image in every 10 seconds from video?
        require_once 'ffmpeglib/vendor/autoload.php'; 
        $folderPath='convert/';
    
        ##Create the required Object
        $ffmpeg = FFMpeg\FFMpeg::create();
        $video = $ffmpeg->open($folderPath.'video.mp4');
    
        for($i=10; $i<=300; $i+=10){
            $video
                ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($i))
                ->save($folderPath.'frame_'.$i.'.jpg');            
    
        }
    



    Question: How to set the binary file path in ffpeg?
    $ffmpeg = FFMpeg\FFMpeg::create(array(
        'ffmpeg.binaries'  => '/opt/local/ffmpeg/bin/ffmpeg',
        'ffprobe.binaries' => '/opt/local/ffmpeg/bin/ffprobe',
        'timeout'          => 3600, // The timeout for the underlying process
        'ffmpeg.threads'   => 12,   // The number of threads that FFMpeg should use
    ));



    Question: How to get the codec_name information of video?
    $ffprobe    = \FFMpeg\FFProbe::create();
    $codeAc=$ffprobe->streams($uploadingFileName[0])
            ->videos()
            ->first()
            ->get('codec_name');
    



    Question: How to get the duration of video?
    $ffprobe    = \FFMpeg\FFProbe::create();
    $codeAc=$ffprobe->streams($uploadingFileName[0])->get('duration');        
    



    Question: How to combine multiple video?
    $staticFilePath='/videopath';
    $video = $ffmpeg->open( $staticFilePath.'0.mp4');
            $video
            ->concat(array($staticFilePath.'0.mp4',$staticFilePath.'1.mp4',$staticFilePath.'2.mp4',$staticFilePath.'3.mp4'))    
            ->saveFromSameCodecs($staticFilePath.'final.mp4', TRUE);
    //final.mp4 will be combined file
    



    Question: How to combine multiple video from h265 to h264?
    $staticFilePath='/videopath';
    $video = $ffmpeg->open( $staticFilePath.'0.mp4');
    $video
            ->concat($array($staticFilePath.'0.mp4',$staticFilePath.'1.mp4',$staticFilePath.'2.mp4',$staticFilePath.'3.mp4'))
            ->saveFromDifferentCodecs(new FFMpeg\Format\Video\X264,$staticFilePath.'final_264.mp4', true);  
    



    Question: How to check file is video file OR Audio file?
    $videoDataAvailable=$ffprobe->streams($videoFile)->videos();
    if(count($videoDataAvailable)==0){
        echo 'AUDIO FILE';
    }else{
        echo 'Video File FILE';
    } 




    Question: How to convert Mp4 to wav using php-ffmpeg?
     
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $ffmpeg = FFMpeg\FFMpeg::create();
    $format = new FFMpeg\Format\Audio\Wav();        
    $videoFolderPath='folder';
    
    
    $audioObj = $ffmpeg->open($videoFolderPath.'/myfile.mp4');    
    $audioObj->save($format, $videoFolderPath.'/myfile.wav'); 
    





    Question: How to convert Mp4 to mp3 using php-ffmpeg?
     
    require_once 'ffmpeglib/vendor/autoload.php'; 
    $ffmpeg = FFMpeg\FFMpeg::create();
    $videoFolderPath='folder';
    
    $mp3Format = new FFMpeg\Format\Audio\Mp3(); 
    $audioObj = $ffmpeg->open($videoFolderPath.'/myfile.mp4');    
    $audioObj->save($mp3Format, $videoFolderPath.'/myfile.mp3'); 
    






    Friday, 6 October 2017

    How to install ffmpeg in wamp server in Windows7

    How to install ffmpeg in wamp server in Windows

    Question: What are Simple steps to install ffmpeg in wamp server in Windows?
    1. Download FFmpeg for Windows
      https://ffmpeg.zeranoe.com/builds/
    2. Extract the downloaded Zip file.
    3. Copy bin/ffmpeg.exe, bin/ffplay.exe and bin/ffprobe.exe from downloaded and paste in C:\Windows\System32
    4. Create a folder with name ffmpegtest in path d:/wamp/www (Drive can be different as per wamp installation)
    5. Login to Command prompt and go to d:/wamp/www/ffmpegtest using cd command
    6. Execute following command (To download composer)
      php -r "readfile('https://getcomposer.org/installer');" | php
      

      It will download the composer.phar
    7. Execute following command to download PHP-FFMPEG library.
      php composer.phar require php-ffmpeg/php-ffmpeg
      
    8. Test the FFMPEG with php
      include "vendor/autoload.php";
      $ffmpeg = FFMpeg\FFMpeg::create();
      print_r($ffmpeg);
      
      When it print the object, means FFMPEG setup successfully.


    Question: What can we do with ffmpeg?
    -Cut the video
    -Combine two or more videos into one
    -Extract the one video portion from main video
    -Resize the video
    -Extract the audio from video
    -Combine photo+audio into video
    -Change the sample rate
    -Watermarking on vi



    Question: What is Bitrate?
    Bitrate describes the rate at which bits are transferred in ffmpeg. Bitrate is commonly measured in bits per second (bps),kilobits per second (Kbps), or megabits per second (Mbps).


    Question: What is Frame Rate?
    the frame rate is the number of frames or images that are projected or displayed per second.


    Question: What is demux?
    A demux(er) is a module responsible for extracting the contents of a given file/stream format, for instance AVI, OGG, MPEG2, WAV, etc.


    Question: How to convert .wav to .mp3?
    include "vendor/autoload.php";
    $ffmpeg = FFMpeg\FFMpeg::create();
    $video = $ffmpeg->open( 'audiofile.wav' );
    $audio_format = new FFMpeg\Format\Audio\Mp3();
    // Extract the audio into a new file as mp3 and save in folder
    $video->save($audio_format, 'audiofile.mp3');
    



    Question: How to transcode a wav to flac?
    include "vendor/autoload.php";
    $ffmpeg = FFMpeg\FFMpeg::create();
    $video = $ffmpeg->open( 'audiofile.wav' );
    $audio_format = new FFMpeg\Format\Audio\Mp3();
    $video->save($audio_format, 'audiofile.mp3');