Record into Buffers


17 March 2011

Today, we had another TAI SIG lecture, this time on creating loops from sounds based on thresholding. Here’s the code we came up with during the course:

s.boot;

// use the GUI to start/stop Ndefs and set additional parameters
NdefMixer(s);

// create an event to put things
q = ();

/* example for event usage
q.class; // event
q.roberto = "sunny"; // add something
q.roberto; // recall value
*/

// create a buffer to record sounds
q.sampleBuffer = Buffer.alloc(s, s.sampleRate * 2.0, 1);

/*
q.sampleBuffer.play; // play Buffer
q.sampleBuffer.plot; // plot Buffer
q.sampleBuffer.zero; // empty Buffer
*/

(
// record sound into buffer as soon as amplitude of signal > threshold
Ndef(record, {|threshold = 0.4, bufnum = 0, recRate = 1|
  var in, amp, trig;

  in = SoundIn.ar(0); // the input signal
  // calculate amplitude of signal with attack-time 0:
  amp = Amplitude.kr(in, 0);
  trig = amp > threshold; // 1 if amp > threshold, 0 else
  trig = Trig.kr(trig, 0.1); // 1 for 0.1 secs

  RecordBuf.ar(
    in, bufnum,
    0, 1, 0, 1, 0,
    trig
  );
});

// set the correct bufnum
Ndef(record).set(bufnum, q.sampleBuffer.bufnum);
)

(
// playback recording every dt seconds with a modulable rate
Ndef(playback, {|bufnum = 0, rate = 1, dt = 4|
  var trig;

  trig = Impulse.kr(1/dt);
  BufRd.ar(
    1,  bufnum,
    EnvGen.ar(
      Env(
        [0, BufFrames.kr(bufnum), 0], // values
        [BufDur.kr(bufnum) * rate.reciprocal, 0], // times
        'linear' // interpolation type
      ),
      gate: trig
    ),
    0, 2
  );
});

Ndef(playback).set(bufnum, q.sampleBuffer.bufnum);
)

/*
// a testbuffer to see if playback does the right thing
q.testBuffer = Buffer.readChannel(
  s, "sounds/SinedPink.aiff", channels: [0]
);
q.testBuffer.plot
Ndef(playback).set(bufnum, q.testBuffer.bufnum);
*/

// cleaning up / destroy the world we created
q.sampleBuffer.free;