SDL_Init(SDL_INIT_AUDIO);
SDL_AudioSpec spec, aspec;
SDL_zero(spec);
spec.freq = 48000; //declare specs
spec.format = AUDIO_S16SYS;
spec.channels = 1;
spec.samples = 4096;
spec.callback = callback;
spec.userdata = NULL;
This portion declares specifications of our audio. We set our sample rate, format, and pass in a callback here.
int id;
if ((id = SDL_OpenAudioDevice(nullptr, 0, &spec, &aspec, SDL_AUDIO_ALLOW_ANY_CHANGE)) <= 0 )
{
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
exit(-1);
}
This opens an audio device and adds it's reference to id. An alternative way of doing the same thing would be to:
SDL_AudioDeviceID audio_device;
audio_device = SDL_OpenAudioDevice(nullptr, 0, &spec, &aspec, SDL_AUDIO_ALLOW_ANY_CHANGE);
//Play A
freq = 440;
SDL_Delay(3000);
//Play middle C
freq = 261.6256;
SDL_Delay(3000);
freq
is a variable that is used in calculations inside the callback. We can modify freq
inside of our while loops to change the "note" of our sound. A has a frequency of 440, so if we set freq
to that value, our sound output changes to that note! Similarly with middle C, which has a frequency of 261.6256. You can find a handy table of piano notes and their frequencies here.
You can also make some fancy sounds by looping through increasing frequencies.
Callback has some interesting code that dictates how sound is produced. Sound is controlled by 2 variables: time
and freq
. Together, they calculate values and place them into a buffer that gets read and played.