How to make audio programatically by SDL2?

Hello men and women!

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.

Sorry, I found something here in the forum:

SDL2 offers two ways to play audio:

  1. You can use a callback function.
#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.

  1. You can use SDL_QueueAudio.
#include "SDL.h"
#include <stdlib.h>
#include <time.h>

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;
	SDL_AudioDeviceID device_id = SDL_OpenAudioDevice(NULL, 0, &spec, NULL, 0);
	
	SDL_PauseAudioDevice(device_id, 0); // start audio
	
	int sample_count = 5 * spec.freq; // 5 seconds
	Sint16* samples = malloc(sample_count * sizeof(Sint16));
	for (int i = 0; i < sample_count; ++i)
	{
		samples[i] = rand() % 30000; // white noise
	}
	
	SDL_QueueAudio(device_id, samples, sample_count * sizeof(Sint16));
	
	free(samples);
	
	while (SDL_GetQueuedAudioSize(device_id) > 0)
	{
		printf("Waiting for sound to finish...\n");
		SDL_Delay(1000);
	}
	
	printf("Done!");
	
	SDL_Quit();
	return 0;
}

See the SDL_AudioSpec wiki page for more information.

What I didnt understand was the math behind it, but I searched now because of the source you shown and found the link:
https://www.adobe.com/uk/creativecloud/video/discover/audio-sampling.html
Good enough for me forgive myself for my sins.

Thank you, man!