-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextensions.sc
930 lines (908 loc) · 25.9 KB
/
extensions.sc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
// my class extensions
XR {
classvar <>fileDict, <>monoFileDict, <>ndefLineSynths;
*initClass { // also using this initClass instead of String's because String already has one.
fileDict = Dictionary.new;
monoFileDict = Dictionary.new;
ndefLineSynths = Dictionary.new;
Server.default.doWhenBooted({
SynthDef(\__speakSynth, {
| bufnum=0 amp=0.5 out=0 |
var reader = DiskIn.ar(1, bufnum, 0);
FreeSelfWhenDone.kr(reader);
Out.ar(out, reader!2 * amp);
}).add;
SynthDef(\line, {
| start=0 end=1 time=1 curve=0 out=0 |
var output;
output = Env([start, start, end, end], [0, time, 0], [0, curve, 0]).kr(2);
Out.kr(out, output);
}).add;
});
}
}
+ Object {
view { // returns a view with the name of this object's class.
/*
ideas for this method:
* 'edit' argument to make the view editable (maybe make a separate method for this?)
* 'change' argument to link the view to 'parent' object, so when this one is changed, the parent is notified...
*/
| parent bounds |
^StaticText(parent, bounds).string_(this.class);
}
makeWindow { // makes a window containing the result of the object's view method.
var win, view;
win = Window(this.class);
view = this.view(win, win.view.bounds).resize_(5);
win.front;
^win;
}
}
+ Symbol {
view {
| parent bounds |
^StaticText(parent, bounds)
.string_(this.asString);
}
desc {
^SynthDescLib.global[this];
}
def {
^this.desc.def;
}
pdef {
^Pdef(this);
}
resendSynthDef {
^((this.def.cs++".add;").interpret);
}
requireSynthDef {
}
bd {
^Bdef(this);
}
bdef {
^Bdef(this);
}
ndef {
^Ndef(this);
}
nd {
^Ndef(this);
}
b {
^Bdef(this).buffer;
}
}
+ String {
split2 { // split a string by a string.
| sep |
var found = this.find(sep);
^if(found.notNil, {
[ this[..(found-1)] ] ++ this[(found+sep.size)..].split2(sep);
}, [ this ]);
}
p { // shortcut for standardizePath because i hate typing long words with CamelCase.
^this.standardizePath;
}
bd {
| item numChannels wavetable |
^Bdef(this, item, numChannels, wavetable);
}
bdef {
| item numChannels wavetable |
^Bdef(this, item, numChannels, wavetable);
}
b {
^this.bd(numChannels:2).buffer;
}
bm {
^this.bd(numChannels:1).buffer;
}
bw {
^this.bd(numChannels:1, wavetable:true).buffer;
}
// b { // buffer
// /*
// Loads a buffer with the sound specified by this string.
// You can call this method as much as you want on the same file because it keeps track of which files are loaded, only reading the file into a new Buffer if one doesn't already exist for the file.
// If the file is already loaded in a buffer via this method, that Buffer is returned.
// This doesn't keep track of freed files, though, so if you free a buffer that you loaded with this method, it will attempt to return that Buffer again, which will probably cause problems.
// If you're going to need to free Buffers, I recommend you write your own Buffer management instead of using this method to load them.
// You can still use the String.convertToWav method to convert songs to a SuperCollider-compatible format, though.
// */
// // FIX - should return instantly, even if conversion is required... Is this possible? For now, calling this method seems to block all other execution. That sucks.
// var the_file = this.p;
// if(the_file[0] != $/, {
// the_file = Platform.resourceDir +/+ the_file;
// });
// if(XR.fileDict.isNil, {
// XR.fileDict = Dictionary.new;
// });
// if(File.exists(the_file), {
// the_file = the_file.convertToWav;
// if(XR.fileDict.includesKey(the_file), {
// ^XR.fileDict[the_file];
// }, {
// var sf = SoundFile.openRead(the_file);
// case( // make sure we return a buffer with 2 channels, since that's what I usually expect...
// { sf.numChannels == 2 }, {
// XR.fileDict[the_file] = Buffer.read(Server.default, the_file);
// },
// { sf.numChannels == 1 }, {
// XR.fileDict[the_file] = Buffer.readChannel(Server.default, the_file, channels:[0,0]);
// },
// { sf.numChannels > 2 }, {
// XR.fileDict[the_file] = Buffer.readChannel(Server.default, the_file, channels:[0,1]);
// },
// );
// sf.close;
// ^XR.fileDict[the_file];
// });
// }, {
// (the_file ++ " was not found.").error;
// });
// }
// bm { // mono buffer - same as the 'b' method above, but loads a mono buffer instead.
// /*
// FIX: there's lots of code duplication here. That means there's probably a better way to write these 2 methods.
// */
// var the_file = this.p;
// if(XR.monoFileDict.isNil, {
// XR.monoFileDict = Dictionary.new;
// });
// if(File.exists(the_file), {
// the_file = the_file.convertToWav;
// if(XR.monoFileDict.includesKey(the_file), {
// ^XR.monoFileDict[the_file];
// }, {
// var sf = SoundFile.openRead(the_file);
// if(sf.numChannels == 1, {
// XR.monoFileDict[the_file] = Buffer.read(Server.default, the_file);
// }, {
// XR.monoFileDict[the_file] = Buffer.readChannel(Server.default, the_file, channels:[0]); // FIX: this only loads the left channel; it should mix the channels together.
// });
// sf.close;
// ^XR.monoFileDict[the_file];
// });
// }, {
// (the_file ++ " was not found.").error;
// });
// }
convertToWav {
/*
If the file specified by this string is not supported for loading by SuperCollider, it is converted to wav using the appropriate program, and then the path to the (temporary) wav file is returned.
*/
var dir = (Platform.defaultTempDir ++ "supercollider").mkdir; // should be a temporary directory so the converted files don't stick around and waste your harddrive space!
var file = this.p;
var output = dir +/+ file.basename.splitext[0] ++ ".wav";
if([\wav, \aif, \aiff].includes((file.basename.splitext[1] ? "").toLower.asSymbol), { // things that don't need to be converted
^file;
}, {
if(File.exists(output), { // the output file already exists(?), so we do nothing and just return the path to it.
^output;
}, { // if the output file doesn't exist, we have to convert it.
("Converting " ++ file ++ "...").postln;
switch(file.splitext[1],
"mp3", {
("lame --decode \"" ++ file ++ "\" \"" ++ output ++ "\" 2>/dev/null").silentCommand;
},
"flac", {
("flac -d \"" ++ file ++ "\" -o \"" ++ output ++ "\" 2>/dev/null").silentCommand;
},
"ogg", {
("oggdec -o \"" ++ output ++ "\" \"" ++ file ++ "\" 2>/dev/null").silentCommand;
},
"m4a", {
("ffmpeg -i \"" ++ file ++ "\" \"" ++ output ++ "\" 2>/dev/null").silentCommand;
},
);
("Done converting " ++ file ++ ".").postln;
^output;
});
});
}
silentCommand { // perform a shell command without showing the output. There might be a better way to do this! (FIX)
var pipe = Pipe.new(this, "r");
var line = pipe.getLine;
while({ line.notNil },
{ line = pipe.getLine; });
pipe.close;
}
asArray {
var res = [];
this.do({
| l |
res = res ++ [l];
});
^res;
}
/*speak { // so Linux users can enjoy the .speak method! Requires the external program 'espeak'.
/*
This is kind of a hackish method. Espeak doesn't support JACK, so it has to be done this way.
I figured I'd include this anyway, since speak is sort of a silly function to begin with.
*/
var rand = 10000.rand;
var dir = (Platform.defaultTempDir ++ "supercollider/").mkdir;
var filename = (dir ++ "/" ++ rand.asString ++ ".wav");
var buf;
("espeak -w \"" ++ filename ++ "\" \"" ++ this.quote ++ "\" &>/dev/null").unixCmd;
fork{
var buf = Buffer.cueSoundFile(Server.default, filename, numChannels: 1);
var synth;
Server.default.sync;
synth = Synth(\speakSynth, [\bufnum, buf]);
NodeWatcher.register(synth);
block {
| break |
loop {
1.wait;
if(synth.isRunning.not, {
buf.free;
break.value;
});
}
}
}
}*/
drumConv {
| symbolmap |
^this.asArray.drumConv(symbolmap);
}
// drumDurConv { // should be like drumConv, but only output durs for \dur, or perhaps note types for \type.
// ^this.drumConv(('*'
// }
view {
| parent bounds |
^StaticText(parent, bounds)
.string_(this);
}
}
+ SimpleNumber { // some math stuff. Some of these might already be built into SC under a different name. Also these might not be correct. If i'm wrong, please tell me!
cpsrate { // frequency to playback rate conversion (to allow you to play UGens like PlayBuf using a normal frequency value)
| base |
base = base ?? { 60.midicps }; // base note defaults to midi note 60
^this/base;
}
ratecps { // FIX: needs fixing(?)
| base |
base = base ?? { 60.midicps };
^base*this;
}
midirate {
// midi note to playback rate conversion
| base |
base = base ? 60;
^this.midicps.cpsrate(base.midicps); // i'm lazy!
}
ratemidi {
| base |
base = base ? 60;
^this.ratecps(base.midicps).cpsmidi; // i'm lazy!
}
// FIX: make these next 2 able to accept a tempo as a number also, and then re-copy them to + UGen.
beatstime { // convert a number of beats to an amount of time (in seconds, of course) based on a TempoClock.
| tempo |
tempo = tempo ?? { TempoClock.default; };
^this*(tempo.beatDur);
}
timebeats {
| tempo |
tempo = tempo ?? { TempoClock.default; };
^this/(tempo.beatDur);
}
transpose { // transpose a frequency value by semitones and/or octaves.
| semitones=0 octaves=0 | // for example: 440.transpose(1) will return a number one semitone higher than 440Hz.
var semi = semitones + (octaves * 12);
^this*(2**(semi/12));
}
remap { // map a number into a spec and out of a different one.
| inspec outspec |
if(outspec.isKindOf(Env), {
outspec.duration_(1);
});
^outspec.asSpec.map(inspec.asSpec.unmap(this));
}
truncString {
| decimals=2 |
var str = this.asString;
var pos = str.find(".");
if(pos.isNil, {
^str;
}, {
^str[..(pos+decimals)];
});
}
}
+ UGen {
cpsrate { // frequency to playback rate conversion (to allow you to play UGens like PlayBuf using a normal frequency value)
| base |
base = base ?? { 60.midicps }; // base note defaults to midi note 60
^this/base;
}
ratecps { // FIX: needs fixing(?)
| base |
base = base ?? { 60.midicps };
^base*this;
}
midirate {
// midi note to playback rate conversion
| base |
base = base ? 60;
^this.midicps.cpsrate(base.midicps); // i'm lazy!
}
ratemidi {
| base |
base = base ? 60;
^this.ratecps(base.midicps).cpsmidi; // i'm lazy!
}
// beatstime { // convert a number of beats to an amount of time (in seconds, of course) based on a TempoClock.
// | tempo |
// tempo = tempo ?? { TempoClock.default; };
// ^this*(tempo.beatDur);
// }
// timebeats {
// | tempo |
// tempo = tempo ?? { TempoClock.default; };
// ^this/(tempo.beatDur);
// }
transpose { // transpose a frequency value by semitones and/or octaves.
| semitones=0 octaves=0 | // for example: 440.transpose(1) will return a number one semitone higher than 440Hz.
var semi = semitones + (octaves * 12);
^this*(2**(semi/12));
}
remap { // map a number into a spec and out of a different one.
| inspec outspec |
if(outspec.isKindOf(Env), {
outspec.duration_(1);
});
^outspec.asSpec.map(inspec.asSpec.unmap(this));
}
// remap {
// | inspec outspec |
// ^this.collect({
// | n |
// n.remap(inspec, outspec);
// });
// }
delay {
| delaytime=0.1 maxdelaytime |
^if(maxdelaytime.isNil, {
DelayL.multiNew(this.rate, this, delaytime, delaytime);
}, {
DelayL.multiNew(this.rate, this, maxdelaytime, delaytime);
});
}
mdelay { // FIX
| delaytimes=0.1 maxdelaytime |
var lb, phase;
maxdelaytime = maxdelaytime??{delaytimes.reduce(\max)};
lb = LocalBuf(Server.default.sampleRate*maxdelaytime, 1);
phase = DelTapWr.ar(lb, this);
^DelTapRd.ar(lb, phase, delaytimes);
}
mdel {
| delaytimes maxdelaytime |
^this.mdelay(delaytimes, maxdelaytime);
}
// transpose {
// | semitones=0 octaves=0 |
// var semi = semitones + (octaves * 12);
// ^(this*(2**(semi/12)));//BinaryOpUGen.new('*', this, (2**(semi/12)));
// }
beatstime {
| tempo |
tempo = tempo ? 1;
^(this*(1/tempo));
}
}
+ Array {
drumConv {
| symbolmap=(()) |
var result = [];
symbolmap = ('*':\kik, '!':\snare1, 'r':\rim, 'k':\kick, 's':\snare1, 'h':\hat, 't':\scratch) ++ symbolmap;
this.do({
| char |
var schar = symbolmap[char.asSymbol];
if(schar.notNil, {
if(schar.isKindOf(Event), {
result = result.add((dur:1/4)++schar);
}, {
result = result.add((instrument: schar, dur: 1/4));
});
}, {
if([$\n, $ ].includes(char).not, {
result = result.add((type: \rest, dur: 1/4));
});
});
});
^Pseq(result);
}
requireSynthDefs {
this.do({
| item |
item.requireSynthDef;
});
}
asEvent {
var res = ();
this.pairsDo({
| e f |
res[e] = f;
});
^res;
}
}
+ SequenceableCollection { //
cpsrate { ^this.performUnaryOp('cpsrate') }
ratecps { ^this.performUnaryOp('ratecps') }
midirate { ^this.performUnaryOp('midirate') }
ratemidi { ^this.performUnaryOp('ratemidi') }
beatstime { ^this.performUnaryOp('beatstime') }
timebeats { ^this.performUnaryOp('timebeats') }
transpose { ^this.performUnaryOp('transpose') }
delay {
| delaytime=0.1 maxdelaytime |
^this.collect({
| i |
i.delay(delaytime, maxdelaytime);
});
}
remap {
| inspec outspec |
^this.collect({
| n |
n.remap(inspec, outspec);
});
}
play { ^this.performUnaryOp('play') }
normalAt {
| index |
^this[(index*this.size).floor];
}
durConv {
/*
converts nested arrays into a pattern.
inspired by Alex McLean's Tidal.
a flat array is array.size beats long.
[\kick, \kick, \kick, \kick].durConv == Pbind(\instrument, \kick, \dur, Pseq([1, 1, 1, 1]))
nested arrays divide that beat by the size of the nested array.
[\kick, [\kick, \kick], \kick, \kick].durConv == Pbind(\instrument, \kick, \dur, Pseq([1, 1/2, 1/2, 1, 1]))
you can also change the parameter that the values are:
(50..53).durConv(param:\midinote) == Pbind(\midinote, Pseq([50, 51, 52, 53]), \dur, Pseq([1, 1, 1, 1]))
or the default duration:
(\kick!4).durConv(1) == Pbind(\instrument, \kick, \dur, Pseq([1/4, 1/4, 1/4, 1/4]))
*/
| dur param nest=0 |
var subdiv = if(this.size != 0, this.size, 1);
var res;
var inst, durs;
param = param?\instrument;
dur = dur ?? { if(this.size != 0, this.size, 1); };
res = this.collect({
| item |
if(item.class == Array, {
item.durConv(dur/subdiv, param, nest+1);
}, {
(\instrument:item, \dur:dur/subdiv);
});
});
if(nest == 0, {
res = res.flat;
inst = res.flat.collect(_[\instrument]);
durs = res.flat.collect(_[\dur]);
^Pbind(param, Pseq(inst), \dur, Pseq(durs));
}, {
^res;
});
}
noteConv {
| bpm |
var notes = [], durs = [], res = [];
this.flat.do {
| current |
var cstr = current.asString;
var durv = [1, 1/2, 1/4][[\w, \h, \q].indexOf(cstr.keep(-1).asSymbol)];
var note = cstr.drop(-1);
notes = notes ++ [if([\, \r, \rest].includes(note.asSymbol), note.asSymbol, {note.notemidi})];
durs = durs ++ [durv];
};
res = [\midinote, Pseq(notes, 1), \dur, Pseq(durs, 1)];
if(bpm.notNil, {
res = res ++ [\tempo, bpm/60];
});
^Pbind(*res);
}
}
+ Event {
trueCompare { // because ('test':5.0, 'sustain':1) == ('test':1.0, 'sustain':1) doesn't return what you'd think it does...
| event |
if(this.keys != event.keys, {
^false;
});
this.keys.do({
| key |
if(this[key] != event[key], {
^false;
});
});
^true;
}
trueAt {
| item |
^this.use({
^item.envirGet.value;
});
}
asArray { // FIX: this might conflict with the default version of this method????
^this.keys.asArray.collect({
| key |
[key.asSymbol, this[key]];
}).flat;
}
expandArrays {
/*
call this method on an Event that has an Array for a key, and all of the elements in that Array will be expanded into individual keys.
in other words:
([\foo, \bar, \baz]: \qux).expandArrays == (\foo: \qux, \bar: \qux, \baz: \qux)
*/
var res = ();
this.keys.do({
| key |
var val = this[key];
if(key.isKindOf(Array), {
key.do({
| item |
res[item] = val;
});
}, {
res[key] = val;
});
});
^res;
}
combineCommonIntoArrays {
/*
provide another Event as an arg and any common keys between the 2 will have their values turned into arrays of the previous values.
i.e.:
(foo:\bar).combineCommonIntoArrays((foo:\baz)) == (foo:[\bar, \baz])
*/
| event |
var res = this.deepCopy;
event.keys.do({
| key |
if(res.keys.includes(key), {
if(res[key].isSequenceableCollection, {
res[key] = res[key] ++
if(event[key].isSequenceableCollection, { event[key] }, { [event[key]] });
}, {
res[key] = [res[key]] ++
if(event[key].isSequenceableCollection, { event[key] }, { [event[key]] });
});
}, {
res[key] = event[key];
});
});
^res;
}
}
+ Buffer {
*readInWavetable {
| file |
var sf, newsize, osig, nsig;
case(
{ file.isKindOf(String) }, {
file = file.p;
sf = SoundFile.openRead(file);
},
{ file.isKindOf(SoundFile) }, {
sf = file;
},
);
newsize = (2**(1..16)).select(_>sf.numFrames)[0];
osig = Signal.newClear(sf.numFrames);
sf.readData(osig);
sf.close;
nsig = osig.resamp1(newsize).as(Signal);
^Buffer.loadCollection(Server.default, nsig.asWavetable);
}
dur { // time in seconds
^(this.numFrames/this.sampleRate);
}
}
+ Node {
setNow { | ... args | // pairs of keys or indices and value
server.sendMsg(*([15, this.nodeID] ++ args));
}
}
+ Synth { // convenience methods!
desc {
^SynthDescLib.global.at(this.defName.asSymbol);
}
info {
^this.desc;
}
controls {
^this.desc.controls;
}
}
+ SynthDef {
*list {
| type=false excludeSystem=true |
/* returns a list of names of all SynthDefs.
'type' can be a symbol or nil, in which case only SynthDefs whose metadata 'type' matches will be listed.
if 'type' is false (the default), all SynthDefs will be listed regardless of their metadata's 'type' value.
if excludeSystem is true (the default), exclude known utility SynthDefs (i.e. for freqScope) as well as SynthDefs whose name begins with an underscore.
*/
var list = SynthDescLib.global.synthDescs;
if(type != false, {
list = list.select({
| sd |
var sdtype = if(sd.metadata.isNil, {
nil;
}, {
sd.metadata[\type];
});
sdtype == type;
});
});
list = list.keys.asArray;
if(excludeSystem, {
var excludeList = (1..16).collect({
| n |
["system_link_audio_", "system_link_control_", "system_diskout_", "freqScope"].collect({
| x |
(x++n).asSymbol;
});
}).flat++[\freqScope0_magresponse_shm, \freqScope1_magresponse_shm, \freqScope0_magresponse, \freqScope1_magresponse, \freqScope0_shm, \freqScope1_shm, \, \freqScope0, \wvst1gl, \wvst0];
list = list.reject(excludeList.includes(_));
list = list.reject({
| e |
e.asString[0] == $_
});
});
^list;
}
memStore {
this.add;
}
}
+ Pattern {
fork { // for compatibility with Pdef(\blah).fork
| clock quant protoEvent |
^this.play(clock, protoEvent, quant);
}
remap { // map a number into a spec and out of a different one.
| inspec outspec |
if(outspec.isKindOf(Env), {
outspec.duration_(1);
});
^outspec.asSpec.map(inspec.asSpec.unmap(this));
}
rec {
| path headerFormat="wav" sampleFormat="float" numChannels=2 dur=nil fadeTime=1 clock(TempoClock.default) protoEvent(Event.default) server(Server.default) out=0 |
var buf, bus, start, recsynth, cmdp, pattern, defname, cond, startTime;
if(dur.notNil) { pattern = Pfindur(dur, this) } { pattern = this };
if(path.isNil, {
if(this.respondsTo(\name), {
path = this.name.asString;
}, {
if(thisProcess.platform.name == \windows) {
path = thisProcess.platform.recordingsDir +/+ "SC_" ++ Main.elapsedTime.round(0.01) ++ "." ++ headerFormat;
} {
path = thisProcess.platform.recordingsDir +/+ "SC_" ++ Date.localtime.stamp ++ "." ++ headerFormat;
};
});
});
if(path[0] != $/, {
path = thisProcess.platform.recordingsDir +/+ path;
});
if(path.basename.splitext[1].isNil, {
path = path ++ "." ++ headerFormat;
});
fork {
cond = Condition.new;
buf = Buffer.alloc(server, 65536, numChannels);
SynthDef(defname = ("patrec"++numChannels).asSymbol, { |bufnum, bus, out|
var sig = In.ar(bus, numChannels);
DiskOut.ar(bufnum, sig);
Out.ar(out, sig);
}).add;
bus = Bus.audio(server, numChannels);
server.sync(cond);
buf.write(path, headerFormat, sampleFormat, numFrames: 0, startFrame: 0, leaveOpen: true);
server.sync(cond);
start = thisThread.beats;
"Recording pattern into % at %\n".postf(path, thisThread.beats);
recsynth = server.nextNodeID;
OSCdef(\__rec, {
| msg time addr recvPort |
if(msg[1] == recsynth, {
cond.unhang;
});
}, '/n_end');
cmdp = {
cond.unhang;
};
CmdPeriod.add(cmdp);
Pprotect(
// Pfset has a cleanupFunc, which executes even if pattern is stopped by cmd-.
Pfset(nil,
Pseq([
Pfuncn({ startTime = thisThread.beats; 0 }),
(type: \on, instrument: defname, bufnum: buf, bus: bus, out: out, id: recsynth,
delta: 0),
pattern <> (out: bus),
Plazy({
Pn((type: \rest, delta: (fadeTime ? 0)
.roundUp(buf.numFrames / server.sampleRate)),
1)
}),
Prout({ (type: \kill, id: recsynth).yield;nil.yield; }),
], 1),
{ (type: \kill, id: recsynth).play }
),
// on error, killing the recsynth triggers rest of cleanup below
{ (type: \kill, id: recsynth).play }
).play(clock, protoEvent, quant: 0);
// clean up after recording synth stops
cond.hang;
OSCdef(\rec).free;
CmdPeriod.remove(cmdp);
buf.close.free;
bus.free;
server.sendMsg(\d_free, defname);
"Finished recording % at % (% s)\n".postf(path, thisThread.beats, (thisThread.beats-start).beatstime);
}
}
}
+ Pdef {
*list {
| excludeSystem=true |
// when excludeSystem is true, exclude "system" patterns, i.e.: '' and all of the patterns whose names start with _.
^Pdef.all.keys.asArray.reject({
| name |
name == '' or: {name.asString[0] == $_};
});
}
}
+ Pbind {
view { // FIX: make this better in the future (allow editing, connect subpatterns' views to this one, etc.).
| parent bounds |
^View(parent, bounds)
.layout_(VLayout(
*this.patternpairs.clump(2).collect({
| clump |
HLayout(*clump.collect(_.view))
})
));
}
}
+ Ndef {
*list {
^Ndef.all.values.collect({|i|i.activeProxies.asArray}).flat;
}
controls {
^this.controlNames;
}
line { // connects a synth to a parameter to smoothly change its value.
| param start end=1 time=1 curve=0 |
var bus, synth, get;
get = this.get(param);
if(get.isKindOf(Symbol), {
bus = Bus.new(\control, get.asString[1..].asInteger, 1);
if(start.isNil, {
start = bus.get;
});
}, {
if(start.isNil, {
start = get;
});
bus = Bus.control(Server.default, 1).set(start);
});
this.set(param, bus.asMap);
Pseq([ // FIX: make it so that this method will free the previous synth if called before the last one ends.
(instrument:\line, start:start, end:end, time:time, curve:curve, out:bus, dur:time.timebeats),
Pfunc({
bus.free;
this.set(param, end);
nil;
}),
]).play;
}
}
+ NodeProxy {
setNow { | ... args | // pairs of keys or indices and value
nodeMap.set(*args);
if(this.isPlaying) {
server.sendMsg(*([15, group.nodeID] ++ args));
}
}
}
+ Env {
*adr {
| attackTime=0.01 decayTime=0.1 sustainLevel=0.5 releaseTime=1.0 peakLevel=1.0 curve=(-4.0) bias=0.0 |
^this.new(
[0, peakLevel, peakLevel * sustainLevel, 0] + bias,
[attackTime, decayTime, releaseTime],
curve
)
}
*line {
| start=0 end=1 time=1 curve=0 |
^this.new([start, start, end], [0, time], [0, curve]);
}
*retrig {
| start=0 end=1 time=1 curve=0 |
^this.line(start, end, time, curve);
}
++ {
| env | // FIX: need releaseNode, loopNode, offset!
^Env(this.levels++env.levels, this.times++[0]++env.times, this.curves++[0]++env.curves.reverse.neg)
}
nearest { // provide the absolute time, and this method will return the index nearest that time.
| time |
^this.times.integrate.indexInBetween(time).round+1;
}
reverse {
^Env(this.levels.reverse, this.times.reverse, this.curves); // FIX: need releaseNode, loopNode, offset!
}
insert { // insert a node into the Env without changing its duration.
| level time curve | // 'time' is absolute
var newlevels, newtimes, newcurves = this.curves.wrapExtend(this.times.size);
if(time <= this.duration, {
var dura = this.times.integrate;
var pos = (dura.indexOfGreaterThan(time));
if(pos == 0, {
newtimes = [time] ++ [this.times[0]-time] ++ this.times[1..];
newlevels = [this.levels[0]] ++ [level] ++ this.levels[1..];
newcurves = [this.curves[0]] ++ newcurves;
}, {
var nt = (time-(dura[pos-1]));
newtimes = this.times.insert(pos, nt);
newtimes = newtimes.put(pos+1, newtimes[pos+1]-nt);
newlevels = this.levels.deepCopy.insert(pos+1, level);
newcurves = newcurves.deepCopy.insert(pos+1, curve??{this.curves.wrapAt(pos)});
});
}, {
newlevels = this.levels ++ [level];
newtimes = this.times ++ [(time-this.duration)];
});
^Env( // FIX: need releaseNode, loopNode, offset!
newlevels,
newtimes,
newcurves
);
}
delete { // delete a node without affecting other nodes or the Env's duration.
| index |
var newlevels = this.levels.deepCopy;
var newtimes = this.times.deepCopy;
var newcurves = if(index == 0, {
this.curves[1..];
}, {
var f = this.curves.deepCopy;
f.removeAt(index);
f;
});
newlevels.removeAt(index);
if(index == 0, {
newtimes.put(0, newtimes.removeAt(0)+newtimes.at(0));
}, {
newtimes.put(index-1, newtimes.removeAt(index-1)+newtimes.at(index-1));
});
^Env(newlevels, newtimes, newcurves); // FIX: need releaseNode, loopNode, offset!
}
}
+ MIDIOut {
*select { // convenience function to select an output & connect a port by part of its name.
| name |
var midiout;
var endpoint = MIDIClient.destinations.select({
| mc |
mc.device.find(name).isNumber;
})[0];
^MIDIOut.newByName(endpoint.device, endpoint.name).connect(MIDIOut.findPort(name));
}
}