Created
May 29, 2019 07:24
-
-
Save superzazu/c0f923181a9cdb82c6d84dcf8b61c8c5 to your computer and use it in GitHub Desktop.
Playing a sine wave with the SDL2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment