Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mvnobrega's avatar

Help with merging in FFMPEG [ SOLVED ]

I'm creating an api with laravel and it needs to merge a video with a background audio. The way I'm doing it is like this:

$code2 = "ffmpeg -i fim.mp4 -stream_loop -1 -i voz.wav -c:v copy -filter_complex \"[0:a]aformat=fltp:44100:stereo,apad[0a];[1]aformat=fltp:44100:stereo,volume=1[1a];[0a][1a]amerge[a]\" -map 0:v -map \"[a]\" -ac 2 -shortest output.mp4";


    system($code2);

Video and audio can have different durations. But I need the audio to repeat only once in the video. This command causes the background audio to be repeated until the end of the video. How do I stop the background audio from repeating until the end of the video?

0 likes
5 replies
rodrigo.pedra's avatar

Remove -stream_loop -1 and maybe also remove -shortest ?

From ffmpeg documentation:

https://ffmpeg.org/ffmpeg.html#Main-options

-stream_loop number (input)

Set number of times input stream shall be looped. Loop 0 means no loop, loop -1 means infinite loop.

-shortest (output)

Finish encoding when the shortest output stream ends.

1 like
mvnobrega's avatar

@rodrigo.pedra

It didn't work but almost...

When the background audio timed out, the video audio was also muted. Any suggestion?

And if I remove the -stream_loop -1 and keep -shortest, the video is shortened to the size of the background audio

Tray2's avatar

This kind of question might be better suited for an ffmpeg forum, or at least one that is geared towards video and audio.

I suggest http:://www.doom9.org or https://videohelp.com

2 likes
mvnobrega's avatar

Thanks for the suggestions.

I found a solution. It merges the two audios first and then takes the image and generates the video:

$code = "ffmpeg -y -i voz.wav -i background.wav -filter_complex \"[0]apad[a];[a][1]amerge[aout]\" -map \"[aout]\" -c:a libmp3lame -q:a 4 output.mp3";

$code1 = "ffmpeg -loop 1 -i result.jpg -i output.mp3 -shortest -acodec copy fim.mp4";

system($code);

system($code1);
1 like

Please or to participate in this conversation.