3

I'm using windows and ffmpeg to convert video mp4 into audio mp3. I've come up with the following batch line that will do the job:

 for %f in (*.mp4); do ffmpeg -i %f -vn -ar 44100 -ac 1 -b:a 32k -f mp3 %f.mp3

However, the %f variable captures the whole filename with the extension, so my output looks like filename.mp4.mp3. I'd rather it look like filename.mp3.

I've tried all sorts of brackets and truncation methods I know of but I cannot get anything to work.

How can I change the filenames in an ffmpeg batch conversion on Windows?

1

2 Answers 2

5

You can extract the file name directly from the for replacement parameter. No need to set a new variable at all.

for %f in (*.mp4) do ffmpeg -i "%f" -vn -ar 44100 -ac 1 -b:a 32k -f mp3 "%~nf.mp3"

If you want to do more complicated string munging, it's much more intuitive in Powershell:

ls *.mp4|foreach{
    ffmpeg -i $_ -vn -ar 44100 -ac 1 -b:a 32k -f mp3 $_.name.replace("mp4", "mp3")
}
8
  • For the first solution, it says set was unexpected at this time.
    – user3643
    Jan 21, 2017 at 23:18
  • Powershell option seems to work. Perhaps I'll just use that. Thank you.
    – user3643
    Jan 21, 2017 at 23:30
  • Dang, typo. I was on my mac so I couldnt' test it. Fixed now.
    – stib
    Jan 22, 2017 at 23:49
  • Output file name now comes out %outfile.mp3. It runs, which is certainly closer, but the output file naming is not working.
    – user3643
    Jan 23, 2017 at 0:28
  • Another typo. It' been a while since I used batch scripting - I do everything in zsh and powershell. Try it again if you like, with luck it should work now..
    – stib
    Jan 23, 2017 at 11:19
1

To add to stib's answer, you can also put this command in a simple batch file. Just save the code below into a .bat file, move the file to the folder you want to work on, then double click it to run. This is assuming you've downloaded and set up ffmpeg.

@echo off
title Extract MP3 from MP4 with FFMPEG. 
rem Mono Channel, 32kbps.
for %%f in (*.mp4) do ffmpeg -i "%%f" -vn -ar 44100 -ac 1 -b:a 32k -f mp3 "%%~nf.mp3"
pause

Notice that the %f variables are now %%f. This is a batch file convention and is required. The script will not run if this is not changed. title is exactly that: the title of the script. rem is short for "remark": it is a comment and you can change that too. Neither lines are actually necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.