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.
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.
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 your
setup()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 to
nil so it will be garbage collected.
You can do this one of two ways:
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.
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.
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…