Playing a WAV File
Changes to Callback?
Playing a wave file involves no real modification to the audio callback used to play a precomputed sine wave, the only changes we'll make are changing Sint16 *sinebuf
to the more general name Sint16 *audiobuf
.
Audio Formats
The WAV file will be written at a certain sampling rate, playing it back at a different sampling rate will distort the sound, so we will not allow SDL to change the sampling rate, or channels or format. We could convert the WAV to match our audio specification using SDL_AudioCvt()
, but why not just edit the WAV in Audacity or something?
We'll play stereo WAVs at 44.1 kHz, so we'll open our device at this rate with 2 channels. This is a normal format you could convert most music to. Playing mono WAVs on a stereo device would put the even samples in the left channel and odd samples in the right, which sounds bad, so we'll exit if the WAV doesn't match our specification.
Actually getting the WAV sound data into memory requires us to use SDL_LoadWAV(char *filename, SDL_AudioSpec *spec, Uint8 **data, int *len)
.
int main(int argc, char** argv) {
if(argc < 2) {
printf("Usage is %s <filename>\n", argv[0]);
return 0;
}
char* filename = argv[1];
/* open wav file, put specification in have, audio location in audiobuf and length in length */
if(!SDL_LoadWAV(filename, &have, &audiobuf, &length)) {
printf("[SDL] Failed to open wav file %s: %s\n", filename, SDL_GetError());
SDL_Quit();
return 1;
}
printf("[SDL] LoadWAV obtained:\nfrequency: %d\nformat - f: %d b: %d channels: %d samples: %d\n", want.freq, SDL_AUDIO_ISFLOAT(want.format), SDL_AUDIO_BITSIZE(want.format), want.channels, want.samples);
/* we only handle one format for now */
if(want.freq != 44100 || want.format != AUDIO_S16 || want.channels != 2) {
printf("WAV file %s is wrong format: requires 44.1 kHz S16 stereo.\n", filename);
SDL_FreeWAV(audiobuf);
SDL_Quit();
return 0;
}
/*
* Initialize and open audio device at 44.1 kHz stereo S16
*/
/*
* Play audio same way as in looped sine example; Cleanup
*/
Exercises / Questions
- How could you display the current position in the audio while playing?
References
https://wiki.libsdl.org/CategoryAudio- Uses javascript SyntaxHighlighter for syntax highlighting.
- Uses javascript MathJax for LateX rendering.
To the extent possible under law,
Craig Hughes
has waived all copyright and related or neighboring rights to
the text and source code in this example/tutorial.