- //RingModulation2.c
- //gcc MKAiff.c RingModulation2.c -o RingModulation2
- #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 modulatorFrequency = 440, carrierFrequency = 500, modulatorAngle = 0;
- int carrierPeriod = SAMPLE_RATE/carrierFrequency;
- float nextCarrierSample;
- int i;
- for(i=0; i<numSamples; i+=NUM_CHANNELS)
- {
- nextCarrierSample = 2 * (i % carrierPeriod) /(float)carrierPeriod - 1;
- audioBuffer[i] = sin(modulatorAngle) * nextCarrierSample;
- modulatorAngle += modulatorFrequency * TWO_PI_OVER_SAMPLE_RATE;
- }
- aiffAppendFloatingPointSamples(aiff, audioBuffer, numSamples, aiffFloatSampleType);
- aiffSaveWithFilename(aiff, "RingModulation2.aif");
- aiffDestroy(aiff);
- return 0;
- }
Output:
Explanation of the Concepts
It may be observed that ring-modulating a sine wave by another sine wave, as was demonstrated in the previous chapter, is somewhat pointless as the result is just two sine-waves with different frequencies than initially specified. More generally interesting results may be produced by modulating a some other wave by a sine wave. Take for instance a sawtooth wave, whose harmonic content looks like this:
When this is ring-modulated by a sine wave, not only will sidebands be produced above and below the fundamental (i.e. carrier+modulator and carrier-modulator), but sidebands will also be produced above and below each overtone. In this case, the result will be carrier+modulator, carrier-modulator; 2*carrier+modulator, 2*carrier-modulator, etc... as can be seen in the spectrum analysis:
From this, it follows that if the modulator frequency and carrier frequency form a consonant interval, the result will be a generally harmonious sound, and if they form a dissonant or non-harmonic interval, as here, the result will be more noisy and non-harmonic. This can be compounded by modulating a non-sine wave by a non-sine wave, which will produce multiple sideband pairs above and below every overtone of the carrier.
Explanation of the Code
There is nothing new in the code here. Refer to the links in the "Builds On" section above for more information.