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

  1. //RingModulation2.c
  2. //gcc MKAiff.c RingModulation2.c -o RingModulation2
  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 modulatorFrequency = 440, carrierFrequency = 500, modulatorAngle = 0;
  18. int carrierPeriod = SAMPLE_RATE/carrierFrequency;
  19. float nextCarrierSample;
  20. int i;
  21. for(i=0; i<numSamples; i+=NUM_CHANNELS)
  22. {
  23. nextCarrierSample = 2 * (i % carrierPeriod) /(float)carrierPeriod - 1;
  24. audioBuffer[i] = sin(modulatorAngle) * nextCarrierSample;
  25. modulatorAngle += modulatorFrequency * TWO_PI_OVER_SAMPLE_RATE;
  26. }
  27. aiffAppendFloatingPointSamples(aiff, audioBuffer, numSamples, aiffFloatSampleType);
  28. aiffSaveWithFilename(aiff, "RingModulation2.aif");
  29. aiffDestroy(aiff);
  30. return 0;
  31. }

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:

SawWave

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:

ModulatedSawWave

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.