Search code examples
windowsbatch-filecmdffmpegforfiles

ffmpeg overwrites input files when called in a forfiles loop


I need to join several mp4 and wav file pairs using ffmpeg.

When I run the command specifying the names of the files, it works well:

.\ffmpeg.exe -i file01.mp4 -i file01.wav -c:v copy -c:a aac -b:a 96k file01_new.mp4

But when I integrate this call in a forfiles loop, the source mp4 file is overwritten and the output mp4 file contains only the audio:

forfiles /M "*.mp4" /C ".\ffmpeg.exe -i @FNAME.mp4 -i @FNAME.wav -c:v copy -c:a aac -b:a 96k @FNAME_new.mp4"

I don't really understand what happens before the MP4 and WAV files are joined. Why is the source MP4 being overwritten?

How do I write this script to make it work? Thank you for your support.


Solution

  • Let me recommend to use for rather than forfiles, because the latter is quite slow and it expands its @-variables with surrounding quotes, which could be problematic:

    rem // Create sub-directory for resulting files, so resulting files cannot become reprocessed:
    2> nul md "result"
    rem // Loop through `*.mp4` files:
    for %%I in ("*.mp4") do (
        rem /* Process current file, together with the related `*.wav` file,
        rem    and write the result into the new sub-directory: */
        ffmpeg.exe -i "%%~I" -i "%%~nI.wav" -c:v copy -c:a aac -b:a 96k "result\%%~I"
    )