An Audio Synthesis Textbook For Musicians, Digital Artists and Programmers by Mike Krzyzaniak
- //Scrubbing.c
- //gcc /usr/include/MKAudio/MKAiff.c Layering.c -o Layering
- #include <MKAudio/MKAiff.h>
- #include <math.h>
- #define PRERECORDED_AUDIO_PATH "/Users/michaelkrzyzaniak/Desktop/demo.aif"
- #define NUM_CHANNELS 2
- #define SAMPLE_RATE 44100
- #define BITS_PER_SAMPLE 16
- #define NUM_SECONDS 5
- #define PI 3.141592653589793
- #define GRAIN_DURATION 0.05
- #define GRAIN_OVERLAP 0.05
- const int framesPerGrain = GRAIN_DURATION * SAMPLE_RATE;
- const int numGrains = NUM_SECONDS / (GRAIN_DURATION * GRAIN_OVERLAP);
- #define GAIN 0.4
- int main()
- {
- MKAiff* preRecordedAudio = aiffWithContentsOfFile(PRERECORDED_AUDIO_PATH);
- if(preRecordedAudio == NULL) return 1;
- MKAiff* aiff = aiffWithDurationInSeconds(NUM_CHANNELS, SAMPLE_RATE, BITS_PER_SAMPLE, NUM_SECONDS);
- if(aiff == NULL) return 1;
- const int samplesPerGrain = NUM_CHANNELS * framesPerGrain;
- float grainBuffer [samplesPerGrain];
- float windowFunction[samplesPerGrain];
- int i, j;
- for(i=0; i<samplesPerGrain; i+=NUM_CHANNELS)
- for(j=0; j<NUM_CHANNELS; j++)
- windowFunction[i+j] = GAIN * 0.5 * (1-cos(2*PI*i/samplesPerGrain));
- //windowFunction[i+j] = GAIN * sin( i*PI / (double)samplesPerGrain );
- float pan, grainLocation;
- for(i=0; i<numGrains; i++)
- {
- pan = random() / (float)RAND_MAX;
- grainLocation = random() / (float)RAND_MAX;
- grainLocation *= (aiffDurationInFrames(preRecordedAudio) - framesPerGrain);
- aiffSetPlayheadToFrames(preRecordedAudio, grainLocation);
- aiffReadFloatingPointSamplesAtPlayhead(preRecordedAudio, grainBuffer, samplesPerGrain);
- for(j=0; j<samplesPerGrain; j+= NUM_CHANNELS)
- {
- grainBuffer[j] *= pan * windowFunction[j];
- grainBuffer[j+1] *= (1-pan) * windowFunction[j];
- }
- aiffSetPlayheadToFrames(aiff, i * framesPerGrain * GRAIN_OVERLAP);
- aiffAddFloatingPointSamplesAtPlayhead(aiff, grainBuffer, samplesPerGrain, aiffFloatSampleType, aiffNo);
- }
- aiffSaveWithFilename(aiff, "Layering.aif");
- aiffDestroy(aiff);
- aiffDestroy(preRecordedAudio);
- return 0;
- }
Output:
Explanation of the Concepts
This example uses granular synthesis to create a dense musical texture.
Conceptually, this example is identical to the previous example, except that here, grains are taken from random locations in the original audio file, rather than successive locations. Also, the grains here are panned to random spacial locations in the stereo field.
Explanation of the Code
Code Explanation