Files
osc/src/voice.cpp
T

50 lines
1.3 KiB
C++
Raw Normal View History

2026-11-14 15:15:00 +06:00
#include "../include/voice.hpp"
2026-11-14 20:37:48 +06:00
std::random_device rd;
std::mt19937 gen(rd());
void Voice::note_on(uint8_t note_, uint8_t velocity){
note = note_;
std::uniform_real_distribution<double> pan_distribution(-1.0, 1.0);
2026-11-14 15:15:00 +06:00
oscillator.frequency = 440.0*std::pow(2.0,( (static_cast<int>(note)-69)/12.0 ));
2026-11-14 20:37:48 +06:00
oscillator.amplitude = (static_cast<double>(velocity) / 127.0);
set_pan(pan_distribution(gen));
2026-11-14 15:15:00 +06:00
envelope.note_on();
active = true;
}
void Voice::note_off(){
envelope.note_off();
2026-11-14 20:37:48 +06:00
if (envelope.is_idle()){
active = false;
}
}
void Voice::set_pan(double value){
pan = std::clamp(value, -1.0, 1.0);
2026-11-14 15:15:00 +06:00
}
2026-11-14 20:37:48 +06:00
StereoSample Voice::generate(){
envelope_value = envelope.process();
if (envelope.is_idle()){
active = false;
}
oscillator.phase = std::fmod(oscillator.phase, (2*std::numbers::pi));
double center = oscillator.amplitude*std::sin(oscillator.phase);
double angle = ((pan+1.0)/2.0)*(std::numbers::pi/2.0);
double left = center*std::cos(angle);
double right = center*std::sin(angle);
oscillator.phase += (2*std::numbers::pi*oscillator.frequency)/(oscillator.sample_rate);
2026-11-14 15:15:00 +06:00
2026-11-14 20:37:48 +06:00
return {left*envelope_value, right*envelope_value};
}
bool Voice::is_active() const {
2026-11-14 15:15:00 +06:00
return active;
}
2026-11-14 20:37:48 +06:00
bool Voice::is_playing(uint8_t note_) const {
return is_active() && note == note_;
}