/** * Great tutorial at: * http://blog.demofox.org/2016/06/16/synthesizing-a-pluked-string-sound-with-the-karplus-strong-algorithm/ * * "If you are looking to synthesize the sound of a plucked string, there is an * amazingly simple algorithm for doing so called the Karplus-Strong Algorithm." * * "It works like this: * 1) Fill a circular buffer with static (random numbers) * 2) Play the contents of the circular buffer over and over * 3) Each time you play a sample, replace that sample with the average of itself * and the next sample in the buffer. Also multiplying that average by a * feedback value (like say, 0.996)" */ var pluckFrequency = 440.0; // Circular buffer length determines the frequency of the plucked string var bufferLength = Math.floor(SAMPLE_RATE / pluckFrequency); var circularBuffer = new Array( bufferLength ); // Step 1: Populate buffer with noise (between -1 and 1) for (var i=0; i<bufferLength; i++) { circularBuffer[i] = Math.random() * 2 - 1; } // TinyRave calls this function 44100 times per second to generate the audio buffer var buildSample = function(time) { var samplesElapsed = Math.floor(time * SAMPLE_RATE); // Step 2: Loop over the circular buffer var bufferIndex = samplesElapsed % bufferLength; var sample = circularBuffer[bufferIndex]; // Get the next sample's index in the curcular buffer so we can keep a running average var nextIndex = (bufferIndex + 1) % bufferLength; // Step 3: Perform a running average as we move over the buffer circularBuffer[bufferIndex] = (circularBuffer[bufferIndex] + circularBuffer[nextIndex]) / 2; // Return the sample from step 2 return sample; }

Watch the 60-sec tutorial