I want to granulate from a sound file, to do it we need to load a sound file into a buffer:
m = Buffer.read(s, "sounds/a11wlk01.wav");
We’re going to set a synth definition:
SynthDef("grain", {arg pan=0.0, rate=1, startPos=0.0, amp=1, dur=0.05; var env = EnvGen.kr(Env.sine(dur, 1), 1.0, doneAction: 2); var synth = PlayBuf.ar(1,buffer, rate, 1, startPos, 0)*env; Out.ar(0,Pan2.ar(synth*amp, pan)) }).send(s);
This synth is based on SC3 PlayBuf UGen. PLayBuf plays a sample from a buffer. Pay attention to startPos parameter: it defines the sample frame to start playback.
We can test our synth evaluating the next sencency:
Synth("grain");
Now we are going to make a loop that plays sample segments. We use random numbers to set the composition parameters.
Task({ var rate, time, dur, startPos; loop{ dur = rrand(0.1, 0.3); rate = rrand(0.7, 1.1); time = exprand(0.1, 2.0); startPos = rrand(0, m.numFrames); Synth("grain", [\dur, dur, \rate, rate, \startPos, startPos, \amp, 1]); time.wait; }; }).play;
I want to open my blog showing a brief introduction to random techniques in music (or simply sound) composition. The example algorithms are going to be implemented in SC3 sound programing environment.
Firstly we need to define a Synth:
SynthDef("grain", { arg dur, frq; var env = EnvGen.kr(Env.sine(dur, 1), 1.0, doneAction:2); var synth = SinOsc.ar(frq)*env; Out.ar(0, Pan2.ar(synth, 0)) }).send(s);
This synth makes a sine wave with a sine envelop. We only need two parameters to get sound with this synth: frequency and duration of the sound. We can test our synth named “grain” evaluating the next sentence in SC3:
Synth("grain", [\dur, 1, \frq, 400]);
After evaluate this sentence we get a sound of 400Hz with one second duration.
We are going to make a loop now! We can get a series of sine waves with the next piece of code:
Task({ var dur = 1; var frq = 400; var time = 1; loop{ Synth("grain", [\dur, dur, \frq, frq]); time.wait; }; }).play;
We can see that we have three new variables: dur, frq and time; the first two are the synth parameters and the third (time) is used to define the time between the start of a sound and the start of the next sound. We can think about these three variables as a parameters of the sound composition.
Now we are going to use a random number generator to get different values for our compositional parameters in each iteration:
Task({ var frq; var time; var dur; loop{ dur = rrand(0.1, 0.3); frq = rrand(300, 1000); time = rrand(0.3, 1.0); Synth("grain", [\dur, dur, \frq, frq]); time.wait; }; }).play;
The rrand(a, b) SC3 function is used to generate random numbers between the parameters a and b.
Just we have seen a simply way to generate some series of sine waves, what can we do now?
- replace rrand() with other random number generators like exprand()
- add to your SynthDef more parameters like amplitude or panning

