When we think of video games, we often think of the music and sounds that accompany them. Providing those special effects used to be very difficult. Keep reading to learn how SDL makes this important task very easy.
To open anything, be it a file or a socket, certain data has to be passed to the environment such as file name, mode and so forth. Opening the audio is no different. The data required to be passed include frequency, format and more. In order to provide these to the environment, SDL_OpenAudio() is used. This method takes two parameters; both are references of type SDL_AudioSpec which is a structure. The members of this structure are:
The freq is an integer representing the frequency of the sound to be played. It is measured in samples per second. The common values are 11025, 22050 and 44100. The higher the value, the higher the frequency and the better the quality.
The format of the audio is represented by format. The data type is UInt16. The format means the size and type of samples being sent. The common value is AUDIO_S16. The other acceptable values include AUDIO_U16 and AUDIO_U8. The U stands for unsigned bits, the S stands for signed bits and the number represents the bits in the samples. Hence the value AUDIO_S16 represents a sample having 16 bits which are unsigned.
Channels is a value that refers to the number of separate channels to be used. A value of 1 indicates that mono (single channel) and a value of 2 indicates that stereo channel must be used.
Samples refers to the size of the audio buffer in samples.
Callback takes the pointer to the function that would be used to fill the audio buffer. The function takes user data, stream and length of the user data as parameters.
Apart from these, the other members include an unsigned 8 bit integer representing silence, UInt32 representing the size of the buffer and a void pointer to the user data.
In code it would look like this:
SDL_AudioSpec wanted; void fill_audio(void *udata, Uint8 *stream, int len);
/* Set the audio format */ wanted.freq = 22050; wanted.format = AUDIO_S16; wanted.channels = 2; /* 1 = mono, 2 = stereo */ wanted.samples = 1024; /* Good low-latency value for callback */ wanted.callback = fill_audio; wanted.userdata = NULL;
where the frequency is 22050, the format to be used is in 16 bit unsigned integer, the channel is stereo, the size of the audio buffer in the sample is 1024 and the function is fill_audio. There is user data to be passed. The next step is playing the audio.