Skip to content

Instantly share code, notes, and snippets.

@superzazu
Created May 29, 2019 07:24
Show Gist options
  • Save superzazu/c0f923181a9cdb82c6d84dcf8b61c8c5 to your computer and use it in GitHub Desktop.
Save superzazu/c0f923181a9cdb82c6d84dcf8b61c8c5 to your computer and use it in GitHub Desktop.
Playing a sine wave with the SDL2
#include <stdio.h>
#include <SDL.h>
int main(void) {
SDL_Init(SDL_INIT_AUDIO);
// the representation of our audio device in SDL:
SDL_AudioDeviceID audio_device;
// opening an audio device:
SDL_AudioSpec audio_spec;
SDL_zero(audio_spec);
audio_spec.freq = 44100;
audio_spec.format = AUDIO_S16SYS;
audio_spec.channels = 1;
audio_spec.samples = 1024;
audio_spec.callback = NULL;
audio_device = SDL_OpenAudioDevice(
NULL, 0, &audio_spec, NULL, 0);
// pushing 3 seconds of samples to the audio buffer:
float x = 0;
for (int i = 0; i < audio_spec.freq * 3; i++) {
x += .010f;
// SDL_QueueAudio expects a signed 16-bit value
// note: "5000" here is just gain so that we will hear something
int16_t sample = sin(x * 4) * 5000;
const int sample_size = sizeof(int16_t) * 1;
SDL_QueueAudio(audio_device, &sample, sample_size);
}
// unpausing the audio device (starts playing):
SDL_PauseAudioDevice(audio_device, 0);
SDL_Delay(3000);
SDL_CloseAudioDevice(audio_device);
SDL_Quit();
return 0;
}
@joshbodily
Copy link

I think you can also queue it in one go after filling up the buffer. May be quicker 🤷?

    Uint32 sample_bytes = as.freq * 3 * sizeof(int16_t);
    int16_t* samples = malloc(sample_bytes);
    float x = 0.0f;
    for (int i = 0; i < as.freq * 3; i++) {
        samples[i] = sin(x * 4) * 5000;
        x += .010f;
    }

    SDL_QueueAudio(audio_device, samples, sample_bytes);
    SDL_PauseAudioDevice(audio_device, 0);

@superzazu
Copy link
Author

I think you can also queue it in one go after filling up the buffer. May be quicker 🤷?

    Uint32 sample_bytes = as.freq * 3 * sizeof(int16_t);
    int16_t* samples = malloc(sample_bytes);
    float x = 0.0f;
    for (int i = 0; i < as.freq * 3; i++) {
        samples[i] = sin(x * 4) * 5000;
        x += .010f;
    }

    SDL_QueueAudio(audio_device, samples, sample_bytes);
    SDL_PauseAudioDevice(audio_device, 0);

Yes, you should do that whenever possible 👍 my code here was voluntarily dumb / unoptimised (error checks are also missing), my goal was to show how to generate and play a sound (without loading it from a file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment