Skip to content

Instantly share code, notes, and snippets.

@mazbox
Created November 30, 2020 14:33
Show Gist options
  • Save mazbox/44079f7610a03cfd3830f09eda656b58 to your computer and use it in GitHub Desktop.
Save mazbox/44079f7610a03cfd3830f09eda656b58 to your computer and use it in GitHub Desktop.
nice fm drum synth
#include "LiveAudio.h"
#include <math.h>
class MyLiveAudio : public LiveAudio {
public:
int pos = 0;
double ph = 0;
float period = 15050;
// these are the coefficients - need to get the scale mapping right
float baseFreq = 50;
// amplitude
float ampCurve = 1.2;
float attackAmt = 40;
float releaseAmt = 10000;
// fm
float ratio = 2.0f;
float fmAmt = 2.0f;
float fmFeedback = 0.1f;
float fmRelease = 5000;
float fmCurve = 1.2;
// pitch
float pitchAmt = 200;
float pitchRelease = 10000;
float pitchCurve = 10;
float lastOp1 = 0.f;
float getSample() {
pos++;
if(pos %((int)period)==0) {
ph = 0;
pos = 0;
}
float env = 0.f;
if(pos<attackAmt) {
env = pos / attackAmt;
} else {
env = 1.f - (pos - attackAmt) / releaseAmt;
if(env<0) env = 0.f;
}
env = pow(env, ampCurve);
float fmEnv = 1.f - (pos / fmRelease);
if(fmEnv<0) fmEnv = 0;
fmEnv = pow(fmEnv, fmCurve);
float pitchEnv = 1.f - (pos / pitchRelease);
if(pitchEnv<0) pitchEnv = 0;
pitchEnv = pow(pitchEnv, pitchCurve);
float op1 = sin(ph*ratio + lastOp1*fmFeedback);
lastOp1 = op1;
float op2 = sin(ph + op1*fmEnv*fmAmt);
float w = 2.0 * M_PI / 44100.f;
ph += w * (baseFreq + pitchEnv * pitchAmt);
return op2 * env;
}
void audioOut(float *samples, int length, int numChans) override {
for(int i = 0; i < length; i++) {
samples[i*2] = samples[i*2+1] = getSample() * 0.1;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment