Skip to content

Commit

Permalink
Piano: Make decay more accurate
Browse files Browse the repository at this point in the history
1. Make decay sample-granular rather than buffer-granular
You only have ~43 buffers per second which can make a jagged signal.

2. Calculate decay in milliseconds
Decay is supposed to be a time value.
  • Loading branch information
willmcpherson2 authored and awesomekling committed Feb 5, 2020
1 parent 44c81ee commit 421a340
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 12 deletions.
28 changes: 18 additions & 10 deletions Applications/Piano/AudioEngine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

AudioEngine::AudioEngine()
{
set_decay(0);
}

AudioEngine::~AudioEngine()
Expand All @@ -45,6 +46,11 @@ void AudioEngine::fill_buffer(FixedArray<Sample>& buffer)
for (size_t note = 0; note < note_count; ++note) {
if (!m_note_on[note])
continue;

m_power[note] -= m_decay_step;
if (m_power[note] < 0)
m_power[note] = 0;

double val = 0;
switch (m_wave) {
case Wave::Sine:
Expand All @@ -70,16 +76,6 @@ void AudioEngine::fill_buffer(FixedArray<Sample>& buffer)
buffer[i].right = buffer[i].left;
}

if (m_decay) {
for (size_t note = 0; note < note_count; ++note) {
if (m_note_on[note]) {
m_power[note] -= m_decay / 100.0;
if (m_power[note] < 0)
m_power[note] = 0;
}
}
}

if (m_delay) {
if (m_delay_buffers.size() >= m_delay) {
auto to_blend = m_delay_buffers.dequeue();
Expand Down Expand Up @@ -201,10 +197,22 @@ void AudioEngine::set_wave(Direction direction)
}
}

static inline double calculate_step(double distance, int milliseconds)
{
if (milliseconds == 0)
return distance;

constexpr double samples_per_millisecond = sample_rate / 1000.0;
double samples = milliseconds * samples_per_millisecond;
double step = distance / samples;
return step;
}

void AudioEngine::set_decay(int decay)
{
ASSERT(decay >= 0);
m_decay = decay;
m_decay_step = calculate_step(1, m_decay);
}

void AudioEngine::set_delay(int delay)
Expand Down
3 changes: 2 additions & 1 deletion Applications/Piano/AudioEngine.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ class AudioEngine {

int m_octave { 4 };
int m_wave { first_wave };
int m_decay { 0 };
int m_decay;
double m_decay_step;
int m_delay { 0 };

int m_time { 0 };
Expand Down
2 changes: 1 addition & 1 deletion Applications/Piano/KnobsWidget.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ KnobsWidget::KnobsWidget(GUI::Widget* parent, AudioEngine& audio_engine, MainWid
m_wave_value->set_text(wave_strings[new_wave]);
};

constexpr int max_decay = 20;
constexpr int max_decay = 1000;
m_decay_knob = GUI::Slider::construct(Orientation::Vertical, m_knobs_container);
m_decay_knob->set_range(0, max_decay);
m_decay_knob->set_value(max_decay - m_audio_engine.decay());
Expand Down

0 comments on commit 421a340

Please sign in to comment.