Skip to content

Instantly share code, notes, and snippets.

@unbit
Created December 4, 2018 10:31
Show Gist options
  • Save unbit/16ff4e04e5efeac67efc7aab81561594 to your computer and use it in GitHub Desktop.
Save unbit/16ff4e04e5efeac67efc7aab81561594 to your computer and use it in GitHub Desktop.
#include <SDL2/SDL.h>
#include <math.h>
#define FREQ 44100
struct note_to_play
{
Uint8 *data;
Uint32 len;
Uint32 offset;
};
static void fill_note(float note_frequency, float *data, int len)
{
float duration = 1.0;
float period = duration / note_frequency;
int number_of_samples_per_period = period * FREQ;
int i = 0;
float value = 0;
for (i = 0; i < FREQ; i++)
{
// note the pointer math data[0] is at address 0, data[1] is at address 4, data[2] is at address 8
data[i] = sinf(value);
value += (M_PI * 2) / (float)number_of_samples_per_period;
}
}
static void fill_audio(void *user_data, Uint8 *stream, int len)
{
struct note_to_play *note = (struct note_to_play *) user_data;
SDL_Log("callback wants %d bytes", len);
// silence
//SDL_memset(stream, 0, len);
if (note->offset + len < note->len)
{
SDL_memcpy(stream, note->data + note->offset, len);
note->offset += len;
}
}
int main(int argc, char **argv)
{
if (SDL_Init(SDL_INIT_AUDIO))
{
SDL_Log("init error: %s", SDL_GetError());
return -1;
}
// get the number of audio devices in the system
int device_num = SDL_GetNumAudioDevices(0);
SDL_Log("found %d sound devices", device_num);
// print the names of audio devices
int i;
for (i = 0; i < device_num; i++)
{
SDL_Log("[%d] %s", i, SDL_GetAudioDeviceName(i, 0));
}
// create a note sample with frequency 880
float *note_buffer = SDL_malloc(sizeof(float) * FREQ);
fill_note(880, note_buffer, FREQ);
// convert from float to sint16
Sint16 *note_s16 = SDL_malloc(sizeof(Sint16) * FREQ);
for (i = 0; i < FREQ; i++)
{
// pointer math note_s16[1] is at address 2, note_buffer[1] is at address 4
note_s16[i] = note_buffer[i] * SDL_MAX_SINT16;
}
SDL_AudioSpec wanted, received;
SDL_memset(&wanted, 0, sizeof(SDL_AudioSpec));
struct note_to_play note;
note.data = (Uint8 *)note_s16;
note.offset = 0;
note.len = sizeof(Sint16) * FREQ;
wanted.channels = 1;
wanted.format = AUDIO_S16;
wanted.freq = FREQ;
wanted.samples = 4096;
wanted.callback = fill_audio;
wanted.userdata = &note;
SDL_AudioDeviceID dev = SDL_OpenAudioDevice(NULL, 0, &wanted, &received, 0);
if (!dev)
{
SDL_Log("open device error: %s", SDL_GetError());
return -1;
}
SDL_PauseAudioDevice(dev, 0);
for (;;)
{
}
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment