- //AcceleratedVibrato.c
- //gcc MKAiff.c AcceleratedVibrato.c -o AcceleratedVibrato
- #include "MKAiff.h"
- #include <math.h>
- #define SAMPLE_RATE 44100
- #define NUM_CHANNELS 1
- #define BITS_PER_SAMPLE 16
- #define NUM_SECONDS 3
- const int numSamples = NUM_SECONDS * NUM_CHANNELS * SAMPLE_RATE;
- #define PI 3.141592653589793
- const double TWO_PI_OVER_SAMPLE_RATE = 2*PI/SAMPLE_RATE;
- int main()
- {
- MKAiff* aiff = aiffWithDurationInSeconds(NUM_CHANNELS, SAMPLE_RATE, BITS_PER_SAMPLE, NUM_SECONDS);
- if(aiff == NULL) return 0;
- float audioBuffer[numSamples];
- double frequency = 440, angle = 0;
- double envelopeDuration=2, startingValue=1, endingValue=7;
- double vibratoFrequency=startingValue, vibratoAngle=0, vibratoDepth=frequency / 100;
- envelopeDuration *= SAMPLE_RATE;
- double envelopeIncrement = ((endingValue - startingValue)/envelopeDuration);
- int i;
- for(i=0; i<numSamples; i+=NUM_CHANNELS)
- {
- audioBuffer[i] = sin(angle);
- angle += (frequency + sin(vibratoAngle) * vibratoDepth) * TWO_PI_OVER_SAMPLE_RATE;
- vibratoAngle += vibratoFrequency * TWO_PI_OVER_SAMPLE_RATE;
- if(i/NUM_CHANNELS < envelopeDuration) vibratoFrequency += envelopeIncrement;
- }
- aiffAppendFloatingPointSamples(aiff, audioBuffer, numSamples, aiffFloatSampleType);
- aiffSaveWithFilename(aiff, "AcceleratedVibrato.aif");
- aiffDestroy(aiff);
- return 0;
- }
Output:
Explanation of the Concepts
Not only can the frequency of an audio wave be modulated, byt the frequency of a sub-audio wave can be modulated as well. In the previous chapter we modulated the frequency of an audio-rate sine wave by a sub-audio-rate sine wave. Here we will modulate the frequency of that subaudio-rate sine wave by a linear envelope. This will cause the rate of the vibrato to change linearly over time. It is important to notice that this particular envelope is not as long as the sound that it is modulating. When the envelope ends, it holds its current value rather than returning to 0, or something else.
Explanation of the Code
This is identical to the previous example, except that the standard variables for a linear envelope have been declared on lines 26 and 27. On line 33, the vibrato sine-wave's value is added to the audio sine-wave's frequency, and on line 37 the envelope's value is added in turn to the vibrato sine-wave.