Generating sound with frequency modulation

In this recipe, we will learn how to modulate a sine wave oscillator using another low frequency sine wave.

We will be basing this recipe on the previous recipe, where the y position of the mouse controlled the frequency of the sine wave; in this recipe, we will use the x position of the mouse to control the modulation frequency.

Getting ready

We will be using the code from the previous recipe, Generating a sine oscillator.

How to do it…

We will multiply the sine wave created in the previous recipe with another low frequency sine wave.

  1. Add the following member variables:
    float mModFrequency;
    float mModPhase, mModPhaseAdd;
  2. Add the following in the setup module to initialize the variables created previously:
    mModFrequency = 0.0f;
    mModPhase = 0.0f;
    mModPhaseAdd = 0.0f;
  3. In the update module, add the following code to calculate the modulation frequency based on the x position of the mouse cursor:
    float maxModFrequency= 30.0f;
    float targetModFrequency= ( getMousePos().x / (float)getWindowWidth() ) * maxModFrequency;
    mModFrequency = math<float>::clamp( targetModFrequency, 0.0f, maxModFrequency );
  4. We will need to calculate another sine wave using mModFrequency, mModPhase, and mModPhaseAdd, and use it to modulate our first sine wave.

    The following is the implementation of audioCallback:

    if( mOutput.size() != ioSampleCount ){
     mOutput.resize( ioSampleCount );
    }
    mPhaseAdd += ( ( mFrequency / 44100.0f ) - mPhaseAdd ) * 0.1f;
    mModPhaseAdd += ( ( mModFrequency / 44100.0f ) - mModPhaseAdd )
      * 0.1f;
    int numChannels= buffer->mNumberChannels;
    for( int i=0; i<ioSampleCount; i++ ){
     mPhase += mPhaseAdd;
     mModPhase += mModPhaseAdd;
     float output = math<float>::sin( mPhase * 2.0f * M_PI ) 
       * math<float>::sin( mModPhase * 2.0f * M_PI );
     for( int j=0; j<numChannels; j++ ){
      buffer->mData[ i*numChannels + j ] = output;
     }
     mOutput[i] = output;
    }
  5. Build and run the application. Move the mouse cursor over the y axis to determine the frequency, and over the x axis to determine the modulation frequency.

We can see how the sine wave created changes in the previous recipe, in the amplitude as it is multiplied by another low frequency sine wave.

How to do it…

How it works…

We calculate a second sine wave with a low frequency oscillation (LFO) and use it to modulate the first sine wave. To modulate the waves, we multiply them by each other.

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

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