Skip to content
Advertisement

How to mix/merge 2 mp3 files in PHP?

I need a tool to join 2 mp3 files in 1.

The first file ( background ) will be some sound ( music, submitted by user ), second file will be a machine (google) speaking text, which was submitted ( by user ).

In output I need a single mp3 file, with background music and speaking robot text playing together.

I can’t really find any PHP standalone solution like some library or something like, only shell commands atc.

So are there some libraries?

or there’s some unique shell command which works on all OS to combine files?

Or how do I complete the task?

Advertisement

Answer

Based off of this question, you should be able to install FFMPEG onto your server (hopefully not a shared host?) and use

//Reduce background volume, assuming it's input2.mp3
shell_exec('ffmpeg -i input2.mp3 -af "volume=0.3" backround.wav');
//Merge the two
shell_exec('ffmpeg -y -i input1.mp3 -i background.wav -filter_complex amerge -c:a libmp3lame -q:a 4 output.mp3');

Then you can simply serve up the output.mp3 file. If this is being performed by PHP running under apache (or other web host, instead of CLI) you’ll need to make sure your www-data user has read access to the input files, and write access to the output directory.

All your temporary output, like the background, should be saved as .wav, and only converted back to .mp3 for the final output. Recompressing the audio at each step may result in a very poor final output.

I am making assumptions about how FFMPEG works here, so you may need to consult the documentation for it in order to build a functioning or more efficient set of commands.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement