In this recipe, we will learn how to add a delay effect to the frequency modulation audio generated in the previous recipe.
We will use the source code from the previous recipe, Generating sound with frequency modulation.
We will store our audio values and play them after an interval to achieve a delay effect using the following steps:
int mDelay; float mMix, mFeedback; vector<float> mDelayLine; int mDelayIndex; int mDelaySize;
Let's initialize the variables created above and initialize our delay line with zeros.
Then add the following in the setup
method:
mDelay = 200; mMix = 0.2f; mFeedback = 0.3f; mDelaySize = mDelay * 44.1f; for( int i=0; i<mDelaySize; i++ ){ mDelayLine.push_back( 0.0f ); }
audioCallback
method, we will read back from the buffer the values that were generated in the frequency modulation and calculate the delay.The final value is again passed into the buffer for output.
Add the following code in the audioCallback
method:
for( int i=0; i<ioSampleCount; i++ ){ float output = buffer->mData[ i*numChannels ]; int readIndex= mDelayIndex - mDelaySize + 1; if( readIndex< 0 ) readIndex += mDelaySize; float delay = mDelayLine[ readIndex * numChannels ]; mDelayLine[ mDelayIndex ] = output + delay * mFeedback; if( ++mDelayIndex == mDelaySize ){ mDelayIndex = 0; } output = math<float>::clamp(output+mMix*delay,-1.0f,1.0f); mOutput[i] = output; for( int j=0; j<numChannels; j++ ){ buffer->mData[ i*numChannels + j ] = output; } }
A delay is an audio effect where an input is stored and then played back after a determined amount of time. We achieve this by creating a buffer the size of mDelay
multiplied by the frequency rate. Each time audioCallback
gets called, we read from the delay line and update the delay line with the current output value. We then add the delay value to the output and advance mDelayIndex
.
18.119.124.49