2cff003e4b
на данном этапе: 1. 8 полифонических голосов 2. ADSR огибающая для каждого голоса 3. MIDI Note On/Note Off 4. стереовыход 5. Equal-Power Panning 6. случайное распределение голосов по стереополю
50 lines
1.3 KiB
C++
50 lines
1.3 KiB
C++
#include "../include/voice.hpp"
|
|
|
|
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);
|
|
oscillator.frequency = 440.0*std::pow(2.0,( (static_cast<int>(note)-69)/12.0 ));
|
|
oscillator.amplitude = (static_cast<double>(velocity) / 127.0);
|
|
set_pan(pan_distribution(gen));
|
|
envelope.note_on();
|
|
active = true;
|
|
}
|
|
|
|
void Voice::note_off(){
|
|
envelope.note_off();
|
|
if (envelope.is_idle()){
|
|
active = false;
|
|
}
|
|
}
|
|
|
|
void Voice::set_pan(double value){
|
|
pan = std::clamp(value, -1.0, 1.0);
|
|
}
|
|
|
|
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);
|
|
|
|
return {left*envelope_value, right*envelope_value};
|
|
}
|
|
|
|
bool Voice::is_active() const {
|
|
return active;
|
|
}
|
|
|
|
bool Voice::is_playing(uint8_t note_) const {
|
|
return is_active() && note == note_;
|
|
}
|