Project: processing-sc / Examples: Buffer.setn
Examples: Buffer.setn
Waveform data drawn within Processing is transmitted to a SuperCollider buffer and played in real-time.
SynthDefs
SynthDef(\playbuf_1, { |bufnum = 0, outbus = 0, amp = 0.5, loop = 0, pan = 0, rate = 1.0| var data; data = PlayBuf.ar(1, bufnum, BufRateScale.kr(bufnum) * rate, 0, 0, loop); FreeSelfWhenDone.kr(data); Out.ar(outbus, Pan2.ar(data, pan, amp)); }).store;
Processing Code
import supercollider.*; float[] samples; Buffer buffer; Synth synth; int prevX = -1, prevY = -1; void setup () { // 1 pixel = 1 sample // - vary the sketch width to alter fundamental frequency. size(512, 256); smooth(); frameRate(30); samples = new float[width]; for (int i = 0; i < width; i++) { samples[i] = sin(TWO_PI * i / width); } buffer = new Buffer(width, 1); buffer.alloc(this, "allocated"); } void allocated (Buffer buffer) { buffer.setn(0, width, samples); synth = new Synth("playbuf_1"); synth.set("loop", 1); synth.set("bufnum", buffer.index); synth.create(); } void draw () { background(20); stroke(255); for (int i = 0; i < samples.length; i++) { point(i, (height * 0.5) + (0.5 * height * samples[i])); } if (!mousePressed) { prevX = -1; prevY = -1; } else { prevX = mouseX; prevY = mouseY; } } void exit() { buffer.free(); synth.free(); super.exit(); } void mouseDragged () { if ((mouseX >= 0) && (mouseX < width) && (prevX < width)) { samples[mouseX] = (2.0 * mouseY / height) - 1.0; if ((prevX > -1) && (prevX != mouseX)) { // Linear interpolation between values - prevents gaps. float curY = prevY; float stepY = ((float) mouseY - prevY) / abs((float) mouseX - prevX); int stepX = (mouseX > prevX) ? 1 : -1; for (int i = 0; i < abs(mouseX - prevX); i++) { samples[prevX + (i * stepX)] = (2.0 * curY / height) - 1.0; curY += stepY; } } buffer.setn(0, width, samples); } }
