Skip to content

Instantly share code, notes, and snippets.

@mazbox
Created July 20, 2020 21:37
Show Gist options
  • Save mazbox/3758b94e8cdd7d6c22f93adce13aebdd to your computer and use it in GitHub Desktop.
Save mazbox/3758b94e8cdd7d6c22f93adce13aebdd to your computer and use it in GitHub Desktop.
Example for making a drum machine with cppsketch
#include "LiveAudio.h"
#include <math.h>
#include <stdlib.h>
class MyLiveAudio : public LiveAudio {
public:
float frac(float f) {
return f - (int)f;
}
float randf() {
return (rand() %10000) / 5000.f - 1.f;
}
int pos = 0;
float env = 0;
int beat = 0;
float freq = 1;
float decay = 0.999;
float freqDecay = 0.999;
float noise = 0.f;
float getSample() {
pos++;
if(pos>7000) {
beat = (beat + 1) % 16;
int seed = 4938 + beat * 151845845845848548584;
if(frac(seed * 1.3498)<0.5) {
env = 1.f;
freq = 1 + 3 * (seed %10);
decay = 1.f - pow(0.1, 3 + 2*frac(seed * 0.9));
freqDecay = 1.f - pow(0.1, 4 + 3*frac(seed * 0.638437));
if(frac(seed * 0.384338)>0.5) {
freqDecay = 2.f - freqDecay;
}
noise = 0.5f * (seed & 1);
}
pos = 0;
}
env *= decay;
freq *= freqDecay;
float out = sin(pos*0.01*freq)*(1 - noise) + randf()*noise;
out = tanh(out * 10.f) * 0.4;
return env*out;
}
void audioOut(float *samples, int length, int numChans) override {
for(int i = 0; i < length; i++) {
samples[i*2] = samples[i*2+1] = getSample();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment