- //SquareSiren.c
- //gcc MKAiff.c SquareSiren.c -o SquareSiren
- #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 sirenFrequency = 7, sirenAmplitude = frequency / 4;
- int sirenHalfWavelength = SAMPLE_RATE / (2*sirenFrequency);
- float nextSirenSample = sirenAmplitude;
- int i;
- for(i=0; i<numSamples; i+=NUM_CHANNELS)
- {
- if(!((i/NUM_CHANNELS) % sirenHalfWavelength))
- nextSirenSample *= -1;
- angle += (frequency + nextSirenSample) * TWO_PI_OVER_SAMPLE_RATE;
- audioBuffer[i] = sin(angle);
- }
- aiffAppendFloatingPointSamples(aiff, audioBuffer, numSamples, aiffFloatSampleType);
- aiffSaveWithFilename(aiff, "SquareSiren.aif");
- aiffDestroy(aiff);
- return 0;
- }
Output:
Explanation of the Concepts
This example modulates the frequency of a sine wave by a square wave. Another way to say that is that a the value of square wave will be added to the frequency of a sine wave. The sine wave is a regular, run-of-the-mill audio-rate sine wave. The square wave, on the other hand, has a frequency of only 7 cycles per second, which would be to low to hear if we tried to send it directly to the speaker. Luckily, we are not sending it to the speaker, we are just replacing the frequency variable of the sine wave with it. To clarify, the plot of the sine wave's frequency of a function of time will look like this:


Explanation of the Code
Line 22 declares the standard variables for the sine wave, and lines 24-26 declare the standard variables for the square wave. Additionally, the square wave's amplitude has also been declared on line 24. This was not necessary in the initial chapter on square-waves, because it was assumed that the wave would simply oscillate between 1 and -1. On line 26 the initial sample of the square wave is set to its amplitude, because it will oscillate between its positive and negative amplitude. Lines 31 and 32 are the typical way of calculating the square wave's value. Lines 34 and 35 are the typical way f calculating the sine-wave's value, except that the value of the square wave is added to the frequency of the sine wave on line 34.