- //Vibrato.c
- //gcc MKAiff.c Vibrato.c -o Vibrato
- #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 vibratoFrequency = 7, vibratoAngle = 0, vibratoDepth = frequency / 100;
- 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;
- }
- aiffAppendFloatingPointSamples(aiff, audioBuffer, numSamples, aiffFloatSampleType);
- aiffSaveWithFilename(aiff, "Vibrato.aif");
- aiffDestroy(aiff);
- return 0;
- }
Output:
Explanation of the Concepts
In the last chapter we modulated the frequency of an audio-rate sine wave by a sub-audio rate square wave. Combining other types of waves produces interesting combinations. Here we will modulate a the frequency of an audio-rate sine wave by another, sub-audio rate, sine wave. This will produce vibrato.
Explanation of the Code
This example is nearly identical to the previous example, except that the square wave has been replace by a sine wave. Notice, again, that the amplitude of the vibrato wave has been declared explicitly on line 23, as the variable called 'vibratoDepth'. Notice, furthermore, that its value has been declared in terms of the frequency of the audio wave.
Since the library function sin() returns a value between 1 and -1, the resultant value for the vibrato wave will have to be multiplied by the amplitude to produce the desired wave. This is accomplished on line 29, and the resultant signal is added to the frequency of the audio wave on the same line.