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');