Created
October 12, 2020 13:58
-
-
Save polyzium/520d2ec98099b306105828633a308fae to your computer and use it in GitHub Desktop.
Simple sine wave synthesizer
This file contains hidden or 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 <iostream> | |
#include <SDL2/SDL.h> | |
#include "oscsine.h" | |
float freq = 440.f; //A4 | |
int samplerate = 44100; | |
OscSine sine(0.5, freq, samplerate); | |
void generate(void* userdata, Uint8* stream, int len) { | |
float *streamf = (float*) stream; //SDL gives uint8, convert to float | |
for (int i=0; i<len/sizeof(float); i++) { | |
streamf[i] = sine.advance(); //Index out of bounds causes a segfault | |
} | |
}; | |
int main() { | |
if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) return 1; | |
SDL_AudioSpec spec; | |
spec.freq = samplerate; | |
spec.format = AUDIO_F32SYS; | |
spec.channels = 1; | |
spec.samples = 512; | |
spec.callback = generate; | |
auto audio = SDL_OpenAudioDevice(nullptr, 0, &spec, &spec, 0); | |
if (audio < 0) std::cerr << "Error: " << SDL_GetError(); | |
SDL_PauseAudioDevice(audio, 0); | |
SDL_Delay(4000); | |
return 0; | |
} |
This file contains hidden or 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 <iostream> | |
#include <math.h> | |
#include "oscsine.h" | |
OscSine::OscSine(float a, float f, int sr) : amp(a), freq(f), samplerate(sr) | |
{ | |
std::cout << "Sine freq " << freq << "\n"; | |
} | |
float OscSine::advance() | |
{ | |
if (amp == 0) return 0.f; //Don't waste computational power if you can't hear it | |
float wave = amp*sin(freq*2*3.1415926*time); | |
time+=1.f/(double)samplerate; | |
return wave; | |
} |
This file contains hidden or 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
#ifndef OSCSINE_H | |
#define OSCSINE_H | |
class OscSine | |
{ | |
public: | |
OscSine(float a, float f, int sr); | |
float amp; | |
float freq; | |
int samplerate; | |
float advance(); | |
private: | |
double time; | |
}; | |
#endif // OSCSINE_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment