-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
oscillator.js
632 lines (586 loc) · 17.8 KB
/
oscillator.js
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
import p5sound from './main';
import Add from 'Tone/signal/Add';
import Mult from 'Tone/signal/Multiply';
import Scale from 'Tone/signal/Scale';
import Panner from './panner';
// ========================== //
// SIGNAL MATH FOR MODULATION //
// ========================== //
function sigChain(nodes, newNode, nodeType, input, output) {
var prevNode = null;
var nextNode = null;
var replacedNode = null;
// If nodes already contains an node of type nodeType, replace that node
// with newNode.
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] instanceof nodeType) {
prevNode = i === 0 ? input : nodes[i - 1];
nextNode = i === nodes.length - 1 ? output : nodes[i + 1];
replacedNode = nodes[i];
nodes[i] = newNode;
break;
}
}
// Otherwise, add newMathOp to the end of mathOps.
if (replacedNode === null) {
prevNode = nodes.length === 0 ? input : nodes[nodes.length - 1];
nextNode = output;
nodes.push(newNode);
}
// Connect the newMathOp to the previous and next nodes.
prevNode.disconnect();
if (replacedNode !== null) {
replacedNode.disconnect();
replacedNode.dispose();
}
prevNode.connect(newNode);
newNode.connect(nextNode);
}
/**
* <p>Creates a signal that oscillates between -1.0 and 1.0.
* By default, the oscillation takes the form of a sinusoidal
* shape ('sine'). Additional types include 'triangle',
* 'sawtooth' and 'square'. The frequency defaults to
* 440 oscillations per second (440Hz, equal to the pitch of an
* 'A' note).</p>
*
* <p>Set the type of oscillation with setType(), or by instantiating a
* specific oscillator: <a href="/reference/#/p5.SinOsc">p5.SinOsc</a>, <a
* href="/reference/#/p5.TriOsc">p5.TriOsc</a>, <a
* href="/reference/#/p5.SqrOsc">p5.SqrOsc</a>, or <a
* href="/reference/#/p5.SawOsc">p5.SawOsc</a>.
* </p>
*
* @class p5.Oscillator
* @constructor
* @param {Number} [freq] frequency defaults to 440Hz
* @param {String} [type] type of oscillator. Options:
* 'sine' (default), 'triangle',
* 'sawtooth', 'square'
* @example
* <div><code>
* let osc, playing, freq, amp;
*
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(playOscillator);
* osc = new p5.Oscillator('sine');
* }
*
* function draw() {
* background(220)
* freq = constrain(map(mouseX, 0, width, 100, 500), 100, 500);
* amp = constrain(map(mouseY, height, 0, 0, 1), 0, 1);
*
* text('tap to play', 20, 20);
* text('freq: ' + freq, 20, 40);
* text('amp: ' + amp, 20, 60);
*
* if (playing) {
* // smooth the transitions by 0.1 seconds
* osc.freq(freq, 0.1);
* osc.amp(amp, 0.1);
* }
* }
*
* function playOscillator() {
* // starting an oscillator on a user gesture will enable audio
* // in browsers that have a strict autoplay policy.
* // See also: userStartAudio();
* osc.start();
* playing = true;
* }
*
* function mouseReleased() {
* // ramp amplitude to 0 over 0.5 seconds
* osc.amp(0, 0.5);
* playing = false;
* }
* </code> </div>
*/
class Oscillator {
constructor(freq, type) {
if (typeof freq === 'string') {
let f = type;
type = freq;
freq = f;
}
if (typeof type === 'number') {
let f = type;
type = freq;
freq = f;
}
this.started = false;
// components
this.phaseAmount = undefined;
this.oscillator = p5sound.audiocontext.createOscillator();
this.f = freq || 440.0; // frequency
this.oscillator.type = type || 'sine';
this.oscillator.frequency.setValueAtTime(
this.f,
p5sound.audiocontext.currentTime
);
// connections
this.output = p5sound.audiocontext.createGain();
this._freqMods = []; // modulators connected to this oscillator's frequency
// set default output gain to 0.5
this.output.gain.value = 0.5;
this.output.gain.setValueAtTime(0.5, p5sound.audiocontext.currentTime);
this.oscillator.connect(this.output);
// stereo panning
this.connection = p5sound.input; // connect to p5sound by default
this.panner = new Panner();
this.output.connect(this.panner);
// array of math operation signal chaining
this.mathOps = [];
// add to the soundArray so we can dispose of the osc later
p5sound.soundArray.push(this);
// these methods are now the same thing
this.fade = this.amp;
}
/**
* Start an oscillator.
*
* Starting an oscillator on a user gesture will enable audio in browsers
* that have a strict autoplay policy, including Chrome and most mobile
* devices. See also: <a href="#/p5/userStartAudio">userStartAudio()</a>.
*
* @method start
* @for p5.Oscillator
* @param {Number} [time] startTime in seconds from now.
* @param {Number} [frequency] frequency in Hz.
*/
start(time, f) {
if (this.started) {
var now = p5sound.audiocontext.currentTime;
this.stop(now);
}
if (!this.started) {
var freq = f || this.f;
var type = this.oscillator.type;
// set old osc free to be garbage collected (memory)
if (this.oscillator) {
this.oscillator.disconnect();
delete this.oscillator;
}
// var detune = this.oscillator.frequency.value;
this.oscillator = p5sound.audiocontext.createOscillator();
this.oscillator.frequency.value = Math.abs(freq);
this.oscillator.type = type;
// this.oscillator.detune.value = detune;
this.oscillator.connect(this.output);
time = time || 0;
this.oscillator.start(time + p5sound.audiocontext.currentTime);
this.freqNode = this.oscillator.frequency;
// if other oscillators are already connected to this osc's freq
for (var i in this._freqMods) {
if (typeof this._freqMods[i].connect !== 'undefined') {
this._freqMods[i].connect(this.oscillator.frequency);
}
}
this.started = true;
}
}
/**
* Stop an oscillator. Accepts an optional parameter
* to determine how long (in seconds from now) until the
* oscillator stops.
*
* @method stop
* @for p5.Oscillator
* @param {Number} [secondsFromNow] Time, in seconds from now.
*/
stop(time) {
if (this.started) {
var t = time || 0;
var now = p5sound.audiocontext.currentTime;
this.oscillator.stop(t + now);
this.started = false;
}
}
/**
* Set the amplitude between 0 and 1.0. Or, pass in an object
* such as an oscillator to modulate amplitude with an audio signal.
*
* @method amp
* @for p5.Oscillator
* @param {Number|Object} vol between 0 and 1.0
* or a modulating signal/oscillator
* @param {Number} [rampTime] create a fade that lasts rampTime
* @param {Number} [timeFromNow] schedule this event to happen
* seconds from now
* @return {AudioParam} gain If no value is provided,
* returns the Web Audio API
* AudioParam that controls
* this oscillator's
* gain/amplitude/volume)
*/
amp(vol, rampTime = 0, tFromNow = 0) {
if (typeof vol === 'number') {
var now = p5sound.audiocontext.currentTime;
this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime);
} else if (vol) {
vol.connect(this.output.gain);
} else {
// return the Gain Node
return this.output.gain;
}
}
/**
* Returns the value of output gain
*
* @method getAmp
* @for p5.Oscillator
*
* @returns {number} Amplitude value between 0.0 and 1.0
*/
getAmp() {
return this.output.gain.value;
}
/**
* Set frequency of an oscillator to a value. Or, pass in an object
* such as an oscillator to modulate the frequency with an audio signal.
*
* @method freq
* @for p5.Oscillator
* @param {Number|Object} Frequency Frequency in Hz
* or modulating signal/oscillator
* @param {Number} [rampTime] Ramp time (in seconds)
* @param {Number} [timeFromNow] Schedule this event to happen
* at x seconds from now
* @return {AudioParam} Frequency If no value is provided,
* returns the Web Audio API
* AudioParam that controls
* this oscillator's frequency
* @example
* <div><code>
* let osc;
*
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(playOscillator);
* osc = new p5.Oscillator(300);
* background(220);
* text('tap to play', 20, 20);
* }
*
* function playOscillator() {
* osc.start();
* osc.amp(0.5);
* // start at 700Hz
* osc.freq(700);
* // ramp to 60Hz over 0.7 seconds
* osc.freq(60, 0.7);
* osc.amp(0, 0.1, 0.7);
* }
* </code></div>
*/
freq(val, rampTime = 0, tFromNow = 0) {
if (typeof val === 'number' && !isNaN(val)) {
this.f = val;
var now = p5sound.audiocontext.currentTime;
if (rampTime === 0) {
this.oscillator.frequency.setValueAtTime(val, tFromNow + now);
} else {
if (val > 0) {
this.oscillator.frequency.exponentialRampToValueAtTime(
val,
tFromNow + rampTime + now
);
} else {
this.oscillator.frequency.linearRampToValueAtTime(
val,
tFromNow + rampTime + now
);
}
}
// reset phase if oscillator has a phase
if (this.phaseAmount) {
this.phase(this.phaseAmount);
}
} else if (val) {
if (val.output) {
val = val.output;
}
val.connect(this.oscillator.frequency);
// keep track of what is modulating this param
// so it can be re-connected if
this._freqMods.push(val);
} else {
// return the Frequency Node
return this.oscillator.frequency;
}
}
/**
* Returns the value of frequency of oscillator
*
* @method getFreq
* @for p5.Oscillator
* @returns {number} Frequency of oscillator in Hertz
*/
getFreq() {
return this.oscillator.frequency.value;
}
/**
* Set type to 'sine', 'triangle', 'sawtooth' or 'square'.
*
* @method setType
* @for p5.Oscillator
* @param {String} type 'sine', 'triangle', 'sawtooth' or 'square'.
*/
setType(type) {
this.oscillator.type = type;
}
/**
* Returns current type of oscillator eg. 'sine', 'triangle', 'sawtooth' or 'square'.
*
* @method getType
* @for p5.Oscillator
* @returns {String} type of oscillator eg . 'sine', 'triangle', 'sawtooth' or 'square'.
*/
getType() {
return this.oscillator.type;
}
/**
* Connect to a p5.sound / Web Audio object.
*
* @method connect
* @for p5.Oscillator
* @param {Object} unit A p5.sound or Web Audio object
*/
connect(unit) {
if (!unit) {
this.panner.connect(p5sound.input);
} else if (unit.hasOwnProperty('input')) {
this.panner.connect(unit.input);
this.connection = unit.input;
} else {
this.panner.connect(unit);
this.connection = unit;
}
if (unit && unit._onNewInput) {
unit._onNewInput(this);
}
}
/**
* Disconnect all outputs
*
* @method disconnect
* @for p5.Oscillator
*/
disconnect() {
if (this.output) {
this.output.disconnect();
}
if (this.panner) {
this.panner.disconnect();
if (this.output) {
this.output.connect(this.panner);
}
}
this.oscMods = [];
}
/**
* Pan between Left (-1) and Right (1).
* See also: <a href="#/p5.SoundFile/pan">Pan Example</a>
*
* @method pan
* @for p5.Oscillator
* @param {Number} panning Number between -1 and 1
* @param {Number} [timeFromNow] schedule this event to happen
* seconds from now
*/
pan(pval, tFromNow) {
this.panner.pan(pval, tFromNow);
}
/**
* Returns the current value of pan position , between Left (-1) and Right (1)
*
* @method getPan
* @for p5.Oscillator
*
* @returns {number} pan position of oscillator , between Left (-1) and Right (1)
*/
getPan() {
return this.panner.getPan();
}
// get rid of the oscillator
dispose() {
// remove reference from soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
if (this.oscillator) {
var now = p5sound.audiocontext.currentTime;
this.stop(now);
this.disconnect();
this.panner.dispose();
this.panner = null;
this.oscillator = null;
}
// if it is a Pulse
if (this.osc2) {
this.osc2.dispose();
}
}
/**
* Set the phase of an oscillator between 0.0 and 1.0.
* In this implementation, phase is a delay time
* based on the oscillator's current frequency.
*
* @method phase
* @for p5.Oscillator
* @param {Number} phase float between 0.0 and 1.0
*/
phase(p) {
var delayAmt = p5.prototype.map(p, 0, 1.0, 0, 1 / this.f);
var now = p5sound.audiocontext.currentTime;
this.phaseAmount = p;
if (!this.dNode) {
// create a delay node
this.dNode = p5sound.audiocontext.createDelay();
// put the delay node in between output and panner
this.oscillator.disconnect();
this.oscillator.connect(this.dNode);
this.dNode.connect(this.output);
}
// set delay time to match phase:
this.dNode.delayTime.setValueAtTime(delayAmt, now);
}
/**
* Add a value to the p5.Oscillator's output amplitude,
* and return the oscillator. Calling this method again
* will override the initial add() with a new value.
*
* @method add
* @for p5.Oscillator
* @param {Number} number Constant number to add
* @return {p5.Oscillator} Oscillator Returns this oscillator
* with scaled output
*
*/
add(num) {
var add = new Add(num);
sigChain(this.mathOps, add, Add, this.oscillator, this.output);
return this;
}
/**
* Multiply the p5.Oscillator's output amplitude
* by a fixed value (i.e. turn it up!). Calling this method
* again will override the initial mult() with a new value.
*
* @method mult
* @for p5.Oscillator
* @param {Number} number Constant number to multiply
* @return {p5.Oscillator} Oscillator Returns this oscillator
* with multiplied output
*/
mult(num) {
var mult = new Mult(num);
sigChain(this.mathOps, mult, Mult, this.oscillator, this.output);
return this;
}
/**
* Scale this oscillator's amplitude values to a given
* range, and return the oscillator. Calling this method
* again will override the initial scale() with new values.
*
* @method scale
* @for p5.Oscillator
* @param {Number} inMin input range minumum
* @param {Number} inMax input range maximum
* @param {Number} outMin input range minumum
* @param {Number} outMax input range maximum
* @return {p5.Oscillator} Oscillator Returns this oscillator
* with scaled output
*/
scale(inMin, inMax, outMin, outMax) {
var mapOutMin, mapOutMax;
if (arguments.length === 4) {
mapOutMin = p5.prototype.map(0, inMin, inMax, outMin, outMax);
mapOutMax = p5.prototype.map(1, inMin, inMax, outMin, outMax);
} else {
mapOutMin = arguments[0];
mapOutMax = arguments[1];
}
var scale = new Scale(mapOutMin, mapOutMax);
sigChain(this.mathOps, scale, Scale, this.oscillator, this.output);
return this;
}
}
// ============================== //
// SinOsc, TriOsc, SqrOsc, SawOsc //
// ============================== //
/**
* Constructor: <code>new p5.SinOsc()</code>.
* This creates a Sine Wave Oscillator and is
* equivalent to <code> new p5.Oscillator('sine')
* </code> or creating a p5.Oscillator and then calling
* its method <code>setType('sine')</code>.
* See p5.Oscillator for methods.
*
* @class p5.SinOsc
* @constructor
* @extends p5.Oscillator
* @param {Number} [freq] Set the frequency
*/
class SinOsc extends Oscillator {
constructor(freq) {
super(freq, 'sine');
}
}
/**
* Constructor: <code>new p5.TriOsc()</code>.
* This creates a Triangle Wave Oscillator and is
* equivalent to <code>new p5.Oscillator('triangle')
* </code> or creating a p5.Oscillator and then calling
* its method <code>setType('triangle')</code>.
* See p5.Oscillator for methods.
*
* @class p5.TriOsc
* @constructor
* @extends p5.Oscillator
* @param {Number} [freq] Set the frequency
*/
class TriOsc extends Oscillator {
constructor(freq) {
super(freq, 'triangle');
}
}
/**
* Constructor: <code>new p5.SawOsc()</code>.
* This creates a SawTooth Wave Oscillator and is
* equivalent to <code> new p5.Oscillator('sawtooth')
* </code> or creating a p5.Oscillator and then calling
* its method <code>setType('sawtooth')</code>.
* See p5.Oscillator for methods.
*
* @class p5.SawOsc
* @constructor
* @extends p5.Oscillator
* @param {Number} [freq] Set the frequency
*/
class SawOsc extends Oscillator {
constructor(freq) {
super(freq, 'sawtooth');
}
}
/**
* Constructor: <code>new p5.SqrOsc()</code>.
* This creates a Square Wave Oscillator and is
* equivalent to <code> new p5.Oscillator('square')
* </code> or creating a p5.Oscillator and then calling
* its method <code>setType('square')</code>.
* See p5.Oscillator for methods.
*
* @class p5.SqrOsc
* @constructor
* @extends p5.Oscillator
* @param {Number} [freq] Set the frequency
*/
class SqrOsc extends Oscillator {
constructor(freq) {
super(freq, 'square');
}
}
export default Oscillator;
export { SinOsc, TriOsc, SawOsc, SqrOsc };