Skip to content

Instantly share code, notes, and snippets.

@ollpu
Last active October 19, 2017 15:37
Show Gist options
  • Save ollpu/a5ef012e59a7838f6727e5f77f2901c7 to your computer and use it in GitHub Desktop.
Save ollpu/a5ef012e59a7838f6727e5f77f2901c7 to your computer and use it in GitHub Desktop.
Bare minimum C++ SDL tone generator
/* Compilation:
Requires libsdl2-dev
$ g++ --std=c++14 -lSDL2 -o gen gen.cpp
*/
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
#include <iostream>
#include <cmath>
using namespace std;
float state = 0;
const int rate = 44100;
float freq = 440;
void audio_callback(void *userdata, Uint8 *_stream, int len) {
// Cast byte stream into 16-bit signed int stream
Sint16 *stream = (Sint16*) _stream;
len /= 2;
for (int i = 0; i < len; ++i) {
stream[i] = ((1<<15)-1) * sin(state);
state += 1./rate*2*M_PI*freq;
state = fmod(state, 2*M_PI);
}
}
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_AUDIO);
SDL_AudioSpec spec;
spec.freq = rate;
spec.format = AUDIO_S16SYS;
spec.channels = 1;
spec.samples = 1024;
spec.callback = audio_callback;
spec.userdata = nullptr;
SDL_AudioSpec obtainedSpec;
SDL_OpenAudio(&spec, &obtainedSpec);
SDL_PauseAudio(0);
float nfreq;
while (cin >> nfreq) {
// Lock the audio thread to safely subsitute the frequency
SDL_LockAudio();
freq = nfreq;
SDL_UnlockAudio();
}
SDL_CloseAudio();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment