An Audio Synthesis Textbook For Musicians, Digital Artists and Programmers by Mike Krzyzaniak

  1. //Vibrato.c
  2. //gcc MKAiff.c Vibrato.c -o Vibrato
  3. #include "MKAiff.h"
  4. #include <math.h>
  5. #define SAMPLE_RATE 44100
  6. #define NUM_CHANNELS 1
  7. #define BITS_PER_SAMPLE 16
  8. #define NUM_SECONDS 3
  9. const int numSamples = NUM_SECONDS * NUM_CHANNELS * SAMPLE_RATE;
  10. #define PI 3.141592653589793
  11. const double TWO_PI_OVER_SAMPLE_RATE = 2*PI/SAMPLE_RATE;
  12. int main()
  13. {
  14. MKAiff* aiff = aiffWithDurationInSeconds(NUM_CHANNELS, SAMPLE_RATE, BITS_PER_SAMPLE, NUM_SECONDS);
  15. if(aiff == NULL) return 0;
  16. float audioBuffer[numSamples];
  17. double frequency = 440, angle = 0;
  18. double vibratoFrequency = 7, vibratoAngle = 0, vibratoDepth = frequency / 100;
  19. int i;
  20. for(i=0; i<numSamples; i+=NUM_CHANNELS)
  21. {
  22. audioBuffer[i] = sin(angle);
  23. angle += (frequency + sin(vibratoAngle) * vibratoDepth) * TWO_PI_OVER_SAMPLE_RATE;
  24. vibratoAngle += vibratoFrequency * TWO_PI_OVER_SAMPLE_RATE;
  25. }
  26. aiffAppendFloatingPointSamples(aiff, audioBuffer, numSamples, aiffFloatSampleType);
  27. aiffSaveWithFilename(aiff, "Vibrato.aif");
  28. aiffDestroy(aiff);
  29. return 0;
  30. }

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.