работа над envelope закончена

envelope работает. без щелчков
This commit is contained in:
2026-11-13 02:02:50 +06:00
parent a92de417b5
commit 3a16ac0c0e
7 changed files with 130 additions and 77 deletions
+4 -1
View File
@@ -33,11 +33,14 @@ class AudioEngine{
int stop();
private:
Synth& synth_;
bool device_is_init = false;
bool device_is_started = false;
Synth& synth_;
ma_device_config config = {};
ma_device device = {};
ma_result result_init;
ma_result result_start;
ma_result result_stop;
+38 -16
View File
@@ -1,7 +1,7 @@
#ifndef ENVELOPE
#define ENVELOPE
#include "../include/synth.hpp"
#include <cstdint>
enum class Condition{
Idle,
@@ -14,29 +14,51 @@ enum class Condition{
class Envelope{
public:
Envelope(Synth& synth) : synth_(synth){
Envelope(){
condition = Condition::Idle;
attack = 0.0;
decay = 0.0;
sustain = 0.0;
release = 0.0;
amplitude = 0.0;
phase = 0.0;
};
attack_time = 0.8;
decay_time = 1.0;
sustain_level = 0.7;
release_time = 0.2;
currnet_amplitude = 0.0;
rate = 0.0;
sample_rate = 48000;
note_is_pressed = false;
}
Envelope(double attack, double decay, double sustain, double release){
condition = Condition::Idle;
attack_time = attack;
decay_time = decay;
sustain_level = sustain;
release_time = release;
currnet_amplitude = 0.0;
rate = 0.0;
sample_rate = 48000;
note_is_pressed = false;
}
void note_on();
void note_off();
double process();
private:
Condition condition;
Synth& synth_;
double attack;
double decay;
double sustain;
double release;
double amplitude;
double phase;
double attack_time;
double decay_time;
double sustain_level;
double release_time;
double currnet_amplitude;
double rate;
uint32_t sample_rate;
bool note_is_pressed;
};
#endif
+8 -3
View File
@@ -4,6 +4,7 @@
#include <cstdint>
#include <numbers>
#include <cmath>
#include "../include/envelope.hpp"
class Synth {
public:
@@ -20,18 +21,22 @@ class Synth {
void set_frequency(double value);
void set_amplitude(double value);
const double get_amplitude();
const double get_phase();
void note_on();
void note_off();
private:
/* 1. частота звука в Герцах
2. громкость звука, от 0 до 1
3. частота дискретизации
4. фаза. от 0 до 2 пи*/
Envelope envelope;
double frequency;
double amplitude;
uint32_t sample_rate;
double phase;
uint32_t sample_rate;
};
#endif
+1
View File
@@ -1,5 +1,6 @@
#include "../include/audio_engine.hpp"
int AudioEngine::start(){
if (device_is_started) throw std::runtime_error("ошибка: повторный запуск");
if (device_is_init){
+67 -49
View File
@@ -1,52 +1,70 @@
/*
* Состояние огибающей
*
П родумай enum class с пятью состояниями: *
- Idle
- Attack
- Decay
- Sustain
- Release
2. Параметры
Добавь четыре параметра ADSR:
- attack;
- decay;
- sustain;
- release.
3. Управление
Предусмотри методы:
- note_on() — начать атаку;
- note_off() — начать отпускание;
- process() — вернуть следующий коэффициент огибающей.
process() должен вызываться для каждого аудиосэмпла, а не один раз на весь буфер.
4. Внутреннее состояние
Тебе понадобится хранить:
- текущее состояние;
- текущий уровень амплитуды;
- прогресс текущей фазы.
Несколько важных условий
1. После note_on() огибающая начинает Attack.
2. После Attack автоматически переходит в Decay.
3. После Decay переходит в Sustain.
4. note_off() переводит огибающую в Release.
5. После Release уровень становится 0, состояние — Idle.
Пока реализуй только структуру класса и переходы между состояниями. Математику изменения амплитуды добавим следующим шагом.
И ещё: в дальнейшем нам понадобится аккуратно организовать передачу команд из main() в аудиопоток. Нельзя бездумно изменять обычные переменные из главного потока, если callback одновременно их читает. Это вопрос потокобезопасности, к которому мы отдельно вернёмся
*/
#include "../include/envelope.hpp"
double Envelope::process(){
amplitude = synth_.get_amplitude();
phase = synth_.get_phase();
return 0.0;
void Envelope::note_on(){
condition = Condition::Attack;
// note_is_pressed = true;
if (attack_time <= 0.0){
attack_time = 0.0001;
}
rate = (1.0 - currnet_amplitude)/(attack_time*sample_rate);
}
void Envelope::note_off(){
if (condition != Condition::Idle){
condition = Condition::Release;
if (release_time <= 0.0){
release_time = 0.0001;
}
rate = (0.0 - currnet_amplitude)/(release_time*sample_rate);
}
// note_is_pressed = false;
}
double Envelope::process(){
switch(condition){
case Condition::Attack:{
currnet_amplitude += rate;
if (currnet_amplitude >= 1.0){
currnet_amplitude = 1.0;
if (decay_time <= 0.0){
condition = Condition::Sustain;
}
else{
condition = Condition::Decay;
rate = (sustain_level - 1.0)/(decay_time*sample_rate);
}
}
return currnet_amplitude;
}
case Condition::Decay:{
currnet_amplitude += rate;
if (currnet_amplitude <= sustain_level){
currnet_amplitude = sustain_level;
condition = Condition::Sustain;
}
return currnet_amplitude;
}
case Condition::Sustain:{
return currnet_amplitude;
}
case Condition::Release:{
currnet_amplitude += rate;
if (currnet_amplitude <= 0.0){
currnet_amplitude = 0.0;
condition = Condition::Idle;
}
return currnet_amplitude;
}
case Condition::Idle:{
return 0.0;
}
default: return 0.0;
}
}
+5 -2
View File
@@ -4,6 +4,7 @@
#include "../include/synth.hpp"
#include "../include/audio_engine.hpp"
int main(){
std::cout << "110.гц\n";
@@ -16,13 +17,15 @@ int main(){
try{
AudioEngine audio_engine(synth);
audio_engine.start();
while (true){
std::cin >> a;
if (a == "start"){
audio_engine.start();
synth.note_on();
}
else audio_engine.stop();
else synth.note_off();
}
// audio_engine.stop();
}
catch (const std::exception& error){
std::cerr << error.what() << "\n";
+7 -6
View File
@@ -1,16 +1,17 @@
#include "../include/synth.hpp"
double Synth::generate(){
phase = std::fmod(phase, (2*std::numbers::pi));
double y = amplitude*std::sin(phase);
phase += (2*std::numbers::pi*frequency)/(sample_rate);
return y;
return y * envelope.process();
}
void Synth::generate_buffer(double* array, int size){
phase = 0;
phase = 0.0;
for (int i = 0; i < size; ++i){
array[i] = generate();
}
@@ -28,10 +29,10 @@ void Synth::set_amplitude(double value){
else amplitude = value;
}
const double Synth::get_amplitude(){
return amplitude;
void Synth::note_on(){
envelope.note_on();
}
cosnt double Synth::get_phase(){
return phase;
void Synth::note_off(){
envelope.note_off();
}