Play WAV files in Codea
Codea has this lovely soundbuffer()
function, but to date there has been no good way to load PCM audio into your app. AND you had to get the raw data, and not something more convenient… like a .WAV file.
Until now. For a personal project I needed the ability to play WAV files, and I figured I would share it with you all.
How do I get it?
You can download a sample project here which will give you the SoundData class, and a sample audio file*.
I will be creating a github project to hold this and other utility classes I will be creating.
How Do I Use It?
Assuming there is a variable named helloSound
that holds the WAV file. All you have to do is:
-- decode the WAV file
soundData = SoundData()
soundData:decodeWavData(helloSound)
-- create a soundbuffer
helloBuffer = soundData:getSoundBuffer()
-- play it
sound(helloBuffer)
You should do the first two steps in yoursetup()
function so the data is ready to play when it is needed. Once you have made a sound buffer there is no need to keep the SoundData class around. So either store it in a local variable, or remember to assign it tonil
so it will be garbage collected.
How Do I Get WAV Files Into My Project?
You can do this one of two ways:
- Using
http.get()
to download the file from the 'net - Embedded in your Codea project using my BString utility (or the like)
Be ware that binary encoded WAV files can be quite large an make your project slow to load. So use lower bit rates and sample sizes if you can.
What Can I Play?
Currently this class supports PCM (aka uncompressed) .WAV files, either mono or stereo, unsigned 8bit or signed 16bit formats. At least that is the theory, I have only tested 8 bit files so far.
Eventually I want to support ADPCM compression as well as straight PCM. It will make the WAV data smaller in your project as well.
I might be convinced to support AIF PCM/ADPCM files, but don’t expect much more than that. I will leave MP3 decoding as an intellectual exercise for the reader.
Resources
For those interested in the WAV file format I recommend this page, it has proved to me more than useful.
*: In case you have ever wondered what that jerk JockM sounds like…