#include "synth.h" #include void play_note(Note *note, float *buffer, unsigned int buffer_size, float sample_rate) { for (unsigned int i = 0; i < buffer_size; i++) { // update phase counter note->phase = note->phase + note->freq / sample_rate; if (note->phase >= 1.0f) { note->phase -= 1.0f; } // oscillator float sample = 0.0f; switch (note->form) { case WAVE_SINE: sample = sinf(2.0f * (float) M_PI * note->phase); break; case WAVE_SAW: sample = 2.0f * note->phase - 1.0f; break; case WAVE_SQUARE: sample = note->phase < 0.5f ? 1.0f : -1.0f; break; case WAVE_TRIANGLE: sample = 4.0f * fabsf(note->phase - 0.5f) - 1.0f; break; default: break; } //note->lp += note->filter_cutoff * (sample - note->lp); //sample = note->lp; // basic attack / release float attack_sec = fmaxf(note->attack_ms / 1000.0f, 1e-6f); // apply minimum value to avoid division by zero float release_sec = fmaxf(note->release_ms / 1000.0f, 1e-6f); // convert attack / release time to a number of steps to reach target gain float attack_step = 0.2f / (attack_sec * sample_rate); float release_step = 0.2f / (release_sec * sample_rate); note->gain = note->is_playing ? fminf(note->gain + attack_step, 0.2f) // attack : fmaxf(note->gain - release_step, 0); // release buffer[i] += sample * note->gain; } }