Friday, January 8, 2010

Automatic .caf file creation

As I said in the previous post, I am currently working on adding sound effects to PewPew 2. The preferred format for sound effects with OpenAL on the iPhone is the .caf (Core Audio Format), but audio softwares usually output .wav files.
Fortunately, there's an easy way to convert one format to the other, using a built in command in OS X:
afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf

Being a programmer, I am lazy, so I started thinking about automatizing the conversion for all my .wav files using a small python script that would look like that:
for every file in the directory:
exec "afconvert -f caff -d LEI16@44100 -c 1 file.wav file.caf"

But it was not going to be efficient: every time I would want to regenerate a single .caf file, the script would regenerate all of them.

And then it hit me: makefiles are made to solve this exact problem. I tested my idea with a small makefile that looked like:
test.caf: test.wav
afconvert -f caff -d LEI16@44100 -c 1 test.wav test.caf
and it worked as expected :-)

I am sure lots of other people thought about using make for stuff other than compilation, but I am still satisfied of having found this on my own.

While I was at it, I did a small python script to generate the makefile. Everytime I create a new wav file, I simply have to run the makefile generator.

Now what's pretty cool is that you can make the makefile run automatically in xCode every time you compile your project. Even cooler is that by executing the makefile with make -j 2 (or make -j 8 for some lucky bastards), you get to exploit all the cores of your CPU for the conversion. Indeed, man make explains that the -j switch "Specifies the number of jobs (commands) to run simultaneously".

Try doing this in Windows. For me, it's clear that OS X and Linux are the best OS for programmers!