I’m studying about emulation and came to me some doubts:
–how can I make audio in SDL2 with C code?
–what is the essentials knowledge to get this?
–some example or repository with them?
–is that all possible or I need other lib? What lib?
NOTE:
I want to make/programming the sound and not use SDL_mixer.
#include "SDL.h"
#include <stdlib.h>
#include <time.h>
void my_audio_callback(void* userdata, Uint8* stream, int length)
{
Sint16* samples = (Sint16*) stream;
int sample_count = length / sizeof(Sint16);
for (int i = 0; i < sample_count; ++i)
{
samples[i] = rand() % 30000; // white noise
}
}
int main(int args, char** argv)
{
srand(time(NULL));
SDL_Init(SDL_INIT_AUDIO);
SDL_AudioSpec spec = {0};
spec.freq = 44100;
spec.format = AUDIO_S16SYS;
spec.channels = 1;
spec.samples = 4096;
spec.callback = my_audio_callback;
SDL_AudioDeviceID device_id = SDL_OpenAudioDevice(NULL, 0, &spec, NULL, 0);
SDL_PauseAudioDevice(device_id, 0); // start audio
SDL_Delay(5000); // wait 5 seconds so that you have a chance to hear the sound
SDL_Quit();
return 0;
}
Note that the callback will run in a separate thread so if you share data between the main thread and the callback thread you might want to use SDL_LockAudioDevice or other synchronization primitives to avoid race conditions.