A MIDI piano synthesizer that implements the Karplus Strong physical modeling algorithm.

Dependencies:   mbed USBDevice PinDetect

Revision:
13:bb0ec927e458
Parent:
9:1e012f67470c
Child:
18:26d93c5b9bb6
--- a/Audio/AudioEngine.cpp	Wed Apr 13 19:48:15 2016 +0000
+++ b/Audio/AudioEngine.cpp	Sun Apr 17 21:35:23 2016 +0000
@@ -20,6 +20,8 @@
         synthesizers[i] = Synthesizer();   
     }
     
+    outputSample = 0.0;
+    
     #if USE_PWM
     audioOut.period(1.0/200000.0);
     #endif
@@ -61,31 +63,28 @@
 }
 
 void AudioEngine::outputAudio() {
-    float output = 0.0;
+    // The first thing we do is output the last calculated sample.
+    // Map [-1, 1] range to [0, 1] range.
+    audioOut = (outputSample + 1.0) / 2.0;
+    
+    // Now reset output and calculate the next sample.
+    outputSample = 0.0;
     
     // Poll all of the synthesizers.
     for (int i = 0; i < C::MAX_POLYPHONY; i++) {
         if (synthesizers[i].isPlaying()) {
-            output += synthesizers[i].getSample();   
+            // Get the next sample.
+            outputSample += synthesizers[i].getSample();   
         } 
     }
     
     // Scale the output by the number of voices.
-    output /= float(C::MAX_POLYPHONY);
+    outputSample /= float(C::MAX_POLYPHONY);
     // Check that we do not clip.
-    if (output > 1.0) {
-        output = 1.0;
-    }
-    if (output < -1.0) {
-        output = -1.0;
+    if (outputSample > 1.0) {
+        outputSample = 1.0;
     }
-    // Map [-1, 1] range to [0, 1] range.
-    audioOut = (output + 1.0) / 2.0;
-    
-    // Go back and process the next sample on all voices.
-    for (int i = 0; i < C::MAX_POLYPHONY; i++) {
-        if (synthesizers[i].isPlaying()) {
-            synthesizers[i].processBuffer();   
-        } 
+    if (outputSample < -1.0) {
+        outputSample = -1.0;
     }
 }
\ No newline at end of file