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.
We will multiply the sine wave created in the previous recipe with another low frequency sine wave.
float mModFrequency; float mModPhase, mModPhaseAdd;
setup
module to initialize the variables created previously:mModFrequency = 0.0f; mModPhase = 0.0f; mModPhaseAdd = 0.0f;
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 );
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; }
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.
18.116.80.34