How to Convert Video to mp3 Audio using PHP with FFmpeg

Category
Tutorial
Reading
5 mins
Views
747
Posting
08 Aug 2024

Media files such as videos are indispensable today for content and other needs, with mp4 and mp3 formats as video and audio formats have become the standard for producing media files. Sometimes we need audio files from a video where we need more help tools such as additional software, but can we extract audio files from videos? The answer is yes.

If you know a programming language it sounds easy, because we can do it quickly. You can use something like Python to do it, but in this tutorial we will discuss how to convert video to mp3 using the PHP programming language without using any libraries and FFmpeg module, here we provide an explanation for Windows use. In this tutorial that we provide is actually simple, not long and not complicated, we only use a few lines of code to run the computational process quickly and efficiently in converting video files into audio.

 

 

How to convert Video to mp3 using PHP with FFmpeg - Genelify

 

1. Installing FFmpeg into the system

Before starting, you are required to install and set the FFmpeg module into your computer first, because in processing the extraction, this module plays an important role in handling it, how do you first download the codex from FFmpeg from this site: https://www.gyan.dev/ffmpeg/builds, it is recommended to use the latest version provided, wait until the download process is complete if you can move the .7z file to the C disk drive, extract the file using software such as Winrar or 7z.

Change the name of the extracted folder to ffmpeg to make it easier, open a command prompt on your computer with Run as Administrator mode, enter the following command:

setx /m PATH "C:\ffmpeg\bin;%PATH%"

 

How to convert Video to mp3 using PHP with FFmpeg - Install FFmpeg 1 - Genelify

If so, please restart your computer and run the ffmpeg -version command in the command prompt to find out the module has been successfully installed on the system.

How to convert Video to mp3 using PHP with FFmpeg - Install FFmpeg 2 - Genelify

Next, we will create the code to process video to mp3 extraction. Besides common video formats such as mp4, you can also use other video formats such as avi, mkv, mov, webm or flv to convert to audio with this module.

 

2. Writing the main PHP code

Before we proceed to write the code, we just remind you once again that this code is recommended to be run on your personal computer, if you plan to make it online or uploaded to a server, make sure that the FFmpeg module is installed on your server and that you use a library that is specialized to handle media file conversion according to your programming language.

If using Python you can use libraries such as moviepy or pydub, in PHP you can use php-ffmpeg or Golang programming language you can use libraries such as go-ffmpeg and so on.

After the installation process of the FFmpeg module is complete, now we enter the most important stage, namely creating code for the video to mp3 extraction process, here we do not use any library, some of the functions we use such as exec which helps to run commands in the shell, if you plan to make it online we recommend that you use the library because the exec function should be disabled for security reasons for your website. First create a new file in the project folder with the file name extract.php, open your editor code and enter the following code:

<?php

// How to convert Video to mp3 using PHP with FFmpeg - Genelify

function convertVideoToMp3(string $inputFile, string $outputFile): bool
{
    // Validation: Check if the video format is supported
    $supportedExtensions = ['mp4', 'avi', 'mkv', 'mov', 'webm', 'flv'];
    $extension = strtolower(pathinfo($inputFile, PATHINFO_EXTENSION));
    if (!in_array($extension, $supportedExtensions)) {
        echo 'Unsupported video format.';
        return false;
    }

    // Path to ffmpeg executable
    $ffmpegPath = 'C:\\ffmpeg\\bin\\ffmpeg';

    // Command to run ffmpeg with necessary arguments
    $command = "$ffmpegPath -i " . escapeshellarg($inputFile) . " " . escapeshellarg($outputFile);

    // Execute the command
    exec($command, $output, $return_var);

    // Return true if conversion was successful, otherwise false
    return $return_var === 0;
}

Navigate ffmpeg in your folder in the $ffmpegPath variable as we exemplified, if the file address is different from what we exemplified, you can adjust it. some explanations of these lines of code:

  • $ffmpegPath: Match the module path to the FFmpeg executable on your system. On Linux it's usually /usr/bin/ffmpeg, while on Windows adjust it to the location of the FFmpeg you downloaded as we did in our example.
  • escapeshellarg: This function is used to avoid command injection and secure the arguments passed to the shell.
  • exec: One of the PHP functions for executing shell commands. The first argument is the command argument while the second and third parameters $output and $return_var are used to capture the output and status of the execution that has been performed.

To run the application, we can use or run the following PHP code after the convertVideoToMp3 function has been created:

<?php

// How to convert Video to mp3 using PHP with FFmpeg - Genelify

// Usage
$inputFile = 'path/to/file.mp4';
$outputFile = 'path/to/file.mp3';

echo convertVideoToMp3($inputFile, $outputFile) ? 'Conversion successful!' : 'Conversion failed!';

Now you have successfully created a simple application to convert video to MP3 using PHP without using libraries and FFmpeg easily locally on your computer system. Maybe you want to ask, what if I want to set the audio bitrate in the PHP code, can I? The answer is yes.

 

3. Adding more arguments in FFmpeg

FFmpeg itself doesn't have direct parameters to set the connection speed or bandwidth. However, you can set some parameters related to quality and compression that can affect the output size and processing time. You can set the audio bitrate to determine the quality and size of the output file. Example:

<?php

// How to convert Video to mp3 using PHP with FFmpeg - Genelify

$command = "$ffmpegPath -i " . escapeshellarg($inputFile) . " -b:a 192k " . escapeshellarg($outputFile);

You can replace the line of code in the $command variable by adding -b:a 192k setting the audio bitrate to 192 kbps, You can set other bitrates such as 128k, 192k, 256k or 320k. In addition, you can also add other parameters to set whether stereo or mono, the frequency of the samples generated or disable video processing, only audio is processed by adding additional parameters to be:

<?php

// How to convert Video to mp3 using PHP with FFmpeg - Genelify

$command = "$ffmpegPath -i " . escapeshellarg($inputFile) . " -vn -ar 44100 -ac 2 -b:a 192k " . escapeshellarg($outputFile);

The explanation of the added arguments is as follows:

  • -vn: This argument serves to disable video processing, only audio will be processed.
  • -ar 44100: Sets how many audio sample frequencies are generated whether 22050, 44100, or 48000 Hz, in this tutorial we use 44100 Hz.
  • -ac 2: Sets how many audio channels are generated whether stereo or mono, for 2 it is stereo, if 1 is mono.

You can set according to your needs for the resulting audio.

 

How to convert Video to mp3 using PHP with FFmpeg - Conversion Successful - Genelify

 

Conclusion

We have successfully converted video files to mp3 using the FFmpeg module and PHP by using shell commands to run the application. While this code is quite effective for conversion of files like mp4 to mp3, there are no direct settings to control the connection speed (KBps) or bandwidth. However, you can control the quality and file size by adjusting the audio bitrate using the -b:a parameter in the FFmpeg command and other arguments.

If you plan to upload applications like this to a server online, you should consider using a more flexible server such as a VPS or cloud-based server, to gain better control over performance and scalability.

Share