Bash – batch convert mp3 files to wav using sox

bashshellsox

for a single .mp3, I can convert it to wav using

sox ./input/filename.mp3 ./output/filename.wav

I tried:

#!/bin/bash
for i in  $(ls *mp3)
do
    sox -t wav $i waves/$(basename $i)
done

But it throws the following error:

sox FAIL formats: can't open input file `filename.mp3': WAVE: RIFF header not found

How would I run this sox conversion over all mp3 files in the input folder and save the generated wav's to the output folder?

PS : I don't know why it shows the file enclosed between a back quote ( ` ) and an apostrophe '

`filename.mp3'

I played all the mp3's and they work perfectly file.

Best Answer

It sounds like you're running into a problem with spaces in the filename. If you have a file named "My Greatest Hits.mp3", your command will try to convert the three different files named "My", "Greatest", and "Hits.mp3". Instead of using the "$()" syntax, just use "*.mp3" in the for line, and make sure to quote the file names in the sox command.

In addition, the basename command doesn't remove the file extension, just any folder names. So this command will create a bunch of WAV files with a ".mp3" extension. Adding "-s .mp3" to the command tells basename to strip the extension, and then put ".wav" on the end adds the correct extension.

Put it all together, and you have this:

for i in *.mp3
do
    sox "$i" "waves/$(basename -s .mp3 "$i").wav"
done
Related Question