Adding a delay effect

In this recipe, we will learn how to add a delay effect to the frequency modulation audio generated in the previous recipe.

Getting ready

We will use the source code from the previous recipe, Generating sound with frequency modulation.

How to do it…

We will store our audio values and play them after an interval to achieve a delay effect using the following steps:

  1. Add the following member variables:
    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 );
    }
  2. In the implementation of our 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;
     } 
    }
  3. Build and run the application. By moving the mouse in the x axis, you control the oscillator frequency, and by moving the mouse in the y axis, you control the modulation frequency. The output will contain a delay effect as shown in the following screenshot:
    How to do it…

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.241.116