Menu

Learning about the SDL_Audio stream

After some investigation and a lot of trial and error, I got audio effects working. In case anybody else happens to come upon this problem, here's some info: the stream provided in the SDL mixaudio callback is PCM data in the format chosen when you set up the mixer. I set up SDL_Audio with the AUDIO_S16SYS flag, which means the stream data is signed (S) 16-bit (16) and uses the system byte ordering (SYS), which on Intel is little-endian. I also chose to use two channels (stereo), so the data for each channel are paired up, making for 32 bits per two-channel "sample" (Two channels of 16 bits each).
A PCM sample for my setup looks like this:
[short: left channel amplitude)][short: right channel amplitude]
Each value is a measure of the amplitude of the waveform for that channel at that discrete point in time, ranging from -32767 to 32767 (range of a short- I'm probably off by one or two.) The sampling rate is the number of these samples that gets processed by the sound driver per second, so in my case, since I'm using 44100 hz (CD sample rate), there'll be 44100 of these 32-bit samples to process each second.
To make noise, for instance a sine wave, you have to create a series of these samples reflecting the amplitude of the sine wave at each sample point. For instance, a repeated series of samples like this:
[0][0] [100][100] [0][0] [-100][-100]
gives you a sine wave with a max amplitude of 100/32767 (pretty quiet) and a period of four samples, giving you a tone a little over 11khz. Repeat the four samples ad nauseum (44100 of them per second) and you've got a sustained sine wave.
To mix audio, you can just add the values of samples together and clamp the resulting value to the min and max of the data type (in my case, short.) This could cause some nasty-sounding clipping but it's a simple solution. (Mixing well is a whole other challenge). So to echo, you add the current sample to the sample from X ms ago, and you have a X ms echo.

Posted by Nick Easler 2010-02-16

Log in to post a comment.