Batch sample rate conversion script for MacOS that maintains folder structure

Sharing my bash script to batch-convert multiple directories of wav files to 48k, preserving the directory structure, within limits - it goes one directory deep.

Conversion is via a utility called ‘sox’. (SoX - Sound eXchange download | SourceForge.net) which can be installed using Homebrew (brew install sox). Homebrew available from https://brew.sh

In my script, sox is invoked calling its gain function, preventing cilpping during conversion.

If you have no idea what I am talking about, there are many other ways to convert that will be easier for you. But if you are comfortable in the shell already. this is very simple.

So for example I have a folder containing other folders with samples in them, such as:

 % ls 
606_SP12		BeatBox			LayeringTools
707_727_vs_SP1200	DMX_vs_SP1200		Vinyl
808_SP1200		LM1_SP1200

To reiterate - each of those folders contain only wav files, not other nested folders.

Put the script into that parent folder, make it executable (chmod +x scriptname.sh), and run it.

It will run for a while and then you’ll find a new directory called ‘converted’ containing the all your sample dirs, with the same names, containing new converted copies of the files with slightly different file names ti differentiate (the file new names are all identical to before but ending …whatever…48000.wav now)

Here is the script:

for i in */*.wav; do
    sr=48000
    file=$(basename $i)
    dir=$(dirname $i)
    basename=${file%.*}
    ext=${file##*.}
    mkdir -p converted/$dir
    sox -G -S $i -r $sr converted/$dir/"$basename $sr.$ext"
done
2 Likes

One other thing to mention - I didn’t write it to handle spaces (" ") in file or directory names. Use an underscore _ instead of a space. I don’t have spaces in the filenames I convert so I didn’t bother.

If you need to replace spaces in filenames for a whole directory with _:

for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
1 Like