How to use FFmpeg to convert uploaded audio file to .mp3 in php

FFmpeg is a free software project that produces libraries and programs for handling multimedia data. How to install FFmpeg on ubuntu operating system 16.04 LTE 32bit.
 sudo apt install ffmpeg

write the below command to check the FFmpeg path.
 whereis ffmpeg

write the below command to check the FFmpeg version.
 ffmpeg -version

let's go through PHP practical exam with upload audio file and convert in to .mp3 audio file.
create file index.php inside your htdocs /test/index.html
 

create folder inside your htdocs /test/uploads
<?php
 ini_set( "max_execution_time", "3600" ); // sets the maximum execution time of this script to 1 hour.
 
 $uploads_dir     = $_SERVER['DOCUMENT_ROOT'].'/test/uploads';
 
 $aditiontmp_name = $_FILES['audio']['tmp_name']; // get client side file tmp_name 
 
 $aditionofileName  = preg_replace('/[^A-Za-z0-9\-_\'.]/', '',$_FILES['audio']['name']); // get client side file name remove the special character with preg_replace function.
 
 $aditionalnewFileName = time()."_".$aditionofileName; //filename changed with current time
 
 if ( move_uploaded_file($aditiontmp_name, "$uploads_dir/$aditionalnewFileName")) //Move uploadedfile
 {
  
  $uploadFile = $uploads_dir."/".$aditionalnewFileName; //Uploaded file path
 
  $ext = pathinfo($uploads_dir."/".$aditionalnewFileName, PATHINFO_EXTENSION); //Get the file extesion.
 
  $uploadFilebasename = basename($uploads_dir."/".$aditionalnewFileName, ".".$ext); //Get the basename of the file without extesion.
  
  $exName = ".mp3";
  
  $finalFile = $uploads_dir."/".$uploadFilebasename.$exName; //Uploaded file name changed with extesion .mp3
  
  $encode_cmd = "/usr/bin/ffmpeg -i $uploadFile -b:a 256000 $finalFile 2>&1"; // -i means input file -b:a means bitrate 2>&1 is use for debug command.

  exec($encode_cmd,$output); //Execute an external program.
  
  echo "
";
  
  echo print_r($output); //  Report of command excution process.

                echo "
"; if($ext !== 'mp3'){ // If the uploaded file mp3 which is not remove from uploaded directory because we need to convert in to .mp3 unlink( $uploadFile ); } chmod( $finalFile, 0644 ); // Set uploaded file the permission. } else { echo "Uploading failed"; //If uploding failed. } ?>

3 comments:

  1. Fabulous post, you have denoted out some fantastic points, I likewise think this s a very wonderful website. I will visit again for more quality contents and also, recommend this site to all. Thanks. YouTube to MP3

    ReplyDelete
  2. Quite a nice post, and I've found another detailed guide on how to convert MKV to MP4 using FFmpeg here, besides, alternative to FFmpeg is mentioned in this guide.

    ReplyDelete

Powered by Blogger.