-
-
Notifications
You must be signed in to change notification settings - Fork 682
/
soundfile.js
1699 lines (1563 loc) · 49.4 KB
/
soundfile.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
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import CustomError from './errorHandler';
import p5sound from './main';
import { midiToFreq, convertToWav, safeBufferSize } from './helpers';
import processorNames from './audioWorklet/processorNames';
import Panner from './panner';
const ac = p5sound.audiocontext;
var _createCounterBuffer = function (buffer) {
const len = buffer.length;
const audioBuf = ac.createBuffer(1, buffer.length, ac.sampleRate);
const arrayBuffer = audioBuf.getChannelData(0);
for (var index = 0; index < len; index++) {
arrayBuffer[index] = index;
}
return audioBuf;
};
/*** SCHEDULE EVENTS ***/
// Cue inspired by JavaScript setTimeout, and the
// Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org
class Cue {
constructor(callback, time, id, val) {
this.callback = callback;
this.time = time;
this.id = id;
this.val = val;
}
}
// event handler to remove references to the bufferSourceNode when it is done playing
function _clearOnEnd(e) {
const thisBufferSourceNode = e.target;
const soundFile = this;
// delete this.bufferSourceNode from the sources array when it is done playing:
thisBufferSourceNode._playing = false;
thisBufferSourceNode.removeEventListener('ended', soundFile._clearOnEnd);
// call the onended callback
soundFile._onended(soundFile);
// delete bufferSourceNode(s) in soundFile.bufferSourceNodes
// iterate in reverse order because the index changes by splice
soundFile.bufferSourceNodes
.map((_, i) => i)
.reverse()
.forEach(function (i) {
const n = soundFile.bufferSourceNodes[i];
if (n._playing === false) {
soundFile.bufferSourceNodes.splice(i, 1);
}
});
if (soundFile.bufferSourceNodes.length === 0) {
soundFile._playing = false;
}
}
/**
* <p>SoundFile object with a path to a file.</p>
*
* <p>The p5.SoundFile may not be available immediately because
* it loads the file information asynchronously.</p>
*
* <p>To do something with the sound as soon as it loads
* pass the name of a function as the second parameter.</p>
*
* <p>Only one file path is required. However, audio file formats
* (i.e. mp3, ogg, wav and m4a/aac) are not supported by all
* web browsers. If you want to ensure compatability, instead of a single
* file path, you may include an Array of filepaths, and the browser will
* choose a format that works.</p>
*
* @class p5.SoundFile
* @constructor
* @param {String|Array} path path to a sound file (String). Optionally,
* you may include multiple file formats in
* an array. Alternately, accepts an object
* from the HTML5 File API, or a p5.File.
* @param {Function} [successCallback] Name of a function to call once file loads
* @param {Function} [errorCallback] Name of a function to call if file fails to
* load. This function will receive an error or
* XMLHttpRequest object with information
* about what went wrong.
* @param {Function} [whileLoadingCallback] Name of a function to call while file
* is loading. That function will
* receive progress of the request to
* load the sound file
* (between 0 and 1) as its first
* parameter. This progress
* does not account for the additional
* time needed to decode the audio data.
*
* @example
* <div><code>
* let mySound;
* function preload() {
* soundFormats('mp3', 'ogg');
* mySound = loadSound('assets/doorbell');
* }
*
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(canvasPressed);
* background(220);
* text('tap here to play', 10, 20);
* }
*
* function canvasPressed() {
* // playing a sound file on a user gesture
* // is equivalent to `userStartAudio()`
* mySound.play();
* }
* </code></div>
*/
class SoundFile {
constructor(paths, onload, onerror, whileLoading) {
if (typeof paths !== 'undefined') {
if (typeof paths === 'string' || typeof paths[0] === 'string') {
var path = p5.prototype._checkFileFormats(paths);
this.url = path;
} else if (typeof paths === 'object') {
if (
!(window.File && window.FileReader && window.FileList && window.Blob)
) {
// The File API isn't supported in this browser
throw 'Unable to load file because the File API is not supported';
}
}
// if type is a p5.File...get the actual file
if (paths.file) {
paths = paths.file;
}
this.file = paths;
}
// private _onended callback, set by the method: onended(callback)
this._onended = function () {};
this._looping = false;
this._playing = false;
this._paused = false;
this._pauseTime = 0;
// cues for scheduling events with addCue() removeCue()
this._cues = [];
this._cueIDCounter = 0;
// position of the most recently played sample
this._lastPos = 0;
this._counterNode = null;
this._workletNode = null;
// array of sources so that they can all be stopped!
this.bufferSourceNodes = [];
// current source
this.bufferSourceNode = null;
this.buffer = null;
this.playbackRate = 1;
this.input = p5sound.audiocontext.createGain();
this.output = p5sound.audiocontext.createGain();
this.reversed = false;
// start and end of playback / loop
this.startTime = 0;
this.endTime = null;
this.pauseTime = 0;
// "restart" would stop playback before retriggering
this.mode = 'sustain';
// time that playback was started, in millis
this.startMillis = null;
// stereo panning
this.panner = new Panner();
this.output.connect(this.panner);
// it is possible to instantiate a soundfile with no path
if (this.url || this.file) {
this.load(onload, onerror);
}
// add this p5.SoundFile to the soundArray
p5sound.soundArray.push(this);
if (typeof whileLoading === 'function') {
this._whileLoading = whileLoading;
} else {
this._whileLoading = function () {};
}
this._clearOnEnd = _clearOnEnd.bind(this);
// same as setVolume, to match Processing Sound
this.amp = this.setVolume;
// these are the same thing
this.fade = this.setVolume;
}
/**
* This is a helper function that the p5.SoundFile calls to load
* itself. Accepts a callback (the name of another function)
* as an optional parameter.
*
* @private
* @for p5.SoundFile
* @param {Function} [successCallback] Name of a function to call once file loads
* @param {Function} [errorCallback] Name of a function to call if there is an error
*/
load(callback, errorCallback) {
var self = this;
var errorTrace = new Error().stack;
if (this.url !== undefined && this.url !== '') {
var request = new XMLHttpRequest();
request.addEventListener(
'progress',
function (evt) {
self._updateProgress(evt);
},
false
);
request.open('GET', this.url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
if (request.status === 200) {
// on sucess loading file:
if (!self.panner) return;
ac.decodeAudioData(
request.response,
// success decoding buffer:
function (buff) {
if (!self.panner) return;
self.buffer = buff;
if (callback) {
callback(self);
}
},
// error decoding buffer. "e" is undefined in Chrome 11/22/2015
function () {
if (!self.panner) return;
var err = new CustomError(
'decodeAudioData',
errorTrace,
self.url
);
var msg = 'AudioContext error at decodeAudioData for ' + self.url;
if (errorCallback) {
err.msg = msg;
errorCallback(err);
} else {
console.error(
msg + '\n The error stack trace includes: \n' + err.stack
);
}
}
);
}
// if request status != 200, it failed
else {
if (!self.panner) return;
var err = new CustomError('loadSound', errorTrace, self.url);
var msg =
'Unable to load ' +
self.url +
'. The request status was: ' +
request.status +
' (' +
request.statusText +
')';
if (errorCallback) {
err.message = msg;
errorCallback(err);
} else {
console.error(
msg + '\n The error stack trace includes: \n' + err.stack
);
}
}
};
// if there is another error, aside from 404...
request.onerror = function () {
var err = new CustomError('loadSound', errorTrace, self.url);
var msg =
'There was no response from the server at ' +
self.url +
'. Check the url and internet connectivity.';
if (errorCallback) {
err.message = msg;
errorCallback(err);
} else {
console.error(
msg + '\n The error stack trace includes: \n' + err.stack
);
}
};
request.send();
} else if (this.file !== undefined) {
var reader = new FileReader();
reader.onload = function () {
if (!self.panner) return;
ac.decodeAudioData(reader.result, function (buff) {
if (!self.panner) return;
self.buffer = buff;
if (callback) {
callback(self);
}
});
};
reader.onerror = function (e) {
if (!self.panner) return;
if (onerror) {
onerror(e);
}
};
reader.readAsArrayBuffer(this.file);
}
}
// TO DO: use this method to create a loading bar that shows progress during file upload/decode.
_updateProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 0.99;
this._whileLoading(percentComplete, evt);
// ...
} else {
// Unable to compute progress information since the total size is unknown
this._whileLoading('size unknown');
}
}
/**
* Returns true if the sound file finished loading successfully.
*
* @method isLoaded
* @for p5.SoundFile
* @return {Boolean}
*/
isLoaded() {
if (this.buffer) {
return true;
} else {
return false;
}
}
/**
* Play the p5.SoundFile
*
* @method play
* @for p5.SoundFile
* @param {Number} [startTime] (optional) schedule playback to start (in seconds from now).
* @param {Number} [rate] (optional) playback rate
* @param {Number} [amp] (optional) amplitude (volume)
* of playback
* @param {Number} [cueStart] (optional) cue start time in seconds
* @param {Number} [duration] (optional) duration of playback in seconds
*/
play(startTime, rate, amp, _cueStart, duration) {
if (!this.output) {
console.warn('SoundFile.play() called after dispose');
return;
}
var now = p5sound.audiocontext.currentTime;
var cueStart, cueEnd;
var time = startTime || 0;
if (time < 0) {
time = 0;
}
time = time + now;
if (typeof rate !== 'undefined') {
this.rate(rate);
}
if (typeof amp !== 'undefined') {
this.setVolume(amp);
}
// TO DO: if already playing, create array of buffers for easy stop()
if (this.buffer) {
// reset the pause time (if it was paused)
this._pauseTime = 0;
// handle restart playmode
if (this.mode === 'restart' && this.buffer && this.bufferSourceNode) {
this.bufferSourceNode.stop(time);
this._counterNode.stop(time);
}
//dont create another instance if already playing
if (this.mode === 'untildone' && this.isPlaying()) {
return;
}
// make a new source and counter. They are automatically assigned playbackRate and buffer
this.bufferSourceNode = this._initSourceNode();
// garbage collect counterNode and create a new one
delete this._counterNode;
this._counterNode = this._initCounterNode();
if (_cueStart) {
if (_cueStart >= 0 && _cueStart < this.buffer.duration) {
// this.startTime = cueStart;
cueStart = _cueStart;
} else {
throw 'start time out of range';
}
} else {
cueStart = 0;
}
if (duration) {
// if duration is greater than buffer.duration, just play entire file anyway rather than throw an error
duration =
duration <= this.buffer.duration - cueStart
? duration
: this.buffer.duration;
}
// if it was paused, play at the pause position
if (this._paused) {
this.bufferSourceNode.start(time, this.pauseTime, duration);
this._counterNode.start(time, this.pauseTime, duration);
} else {
this.bufferSourceNode.start(time, cueStart, duration);
this._counterNode.start(time, cueStart, duration);
}
this._playing = true;
this._paused = false;
// add source to sources array, which is used in stopAll()
this.bufferSourceNodes.push(this.bufferSourceNode);
this.bufferSourceNode._arrayIndex = this.bufferSourceNodes.length - 1;
this.bufferSourceNode.addEventListener('ended', this._clearOnEnd);
}
// If soundFile hasn't loaded the buffer yet, throw an error
else {
throw 'not ready to play file, buffer has yet to load. Try preload()';
}
// if looping, will restart at original time
this.bufferSourceNode.loop = this._looping;
this._counterNode.loop = this._looping;
if (this._looping === true) {
cueEnd = duration ? duration : cueStart - 0.000000000000001;
this.bufferSourceNode.loopStart = cueStart;
this.bufferSourceNode.loopEnd = cueEnd;
this._counterNode.loopStart = cueStart;
this._counterNode.loopEnd = cueEnd;
}
}
/**
* p5.SoundFile has two play modes: <code>restart</code> and
* <code>sustain</code>. Play Mode determines what happens to a
* p5.SoundFile if it is triggered while in the middle of playback.
* In sustain mode, playback will continue simultaneous to the
* new playback. In restart mode, play() will stop playback
* and start over. With untilDone, a sound will play only if it's
* not already playing. Sustain is the default mode.
*
* @method playMode
* @for p5.SoundFile
* @param {String} str 'restart' or 'sustain' or 'untilDone'
* @example
* <div><code>
* let mySound;
* function preload(){
* mySound = loadSound('assets/Damscray_DancingTiger.mp3');
* }
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(canvasPressed);
* noFill();
* rect(0, height/2, width - 1, height/2 - 1);
* rect(0, 0, width - 1, height/2);
* textAlign(CENTER, CENTER);
* fill(20);
* text('restart', width/2, 1 * height/4);
* text('sustain', width/2, 3 * height/4);
* }
* function canvasPressed() {
* if (mouseX < height/2) {
* mySound.playMode('restart');
* } else {
* mySound.playMode('sustain');
* }
* mySound.play();
* }
*
* </code></div>
*/
playMode(str) {
var s = str.toLowerCase().trim();
// if restart, stop all other sounds from playing
if (s === 'restart' && this.buffer && this.bufferSourceNode) {
for (var i = 0; i < this.bufferSourceNodes.length; i++) {
var now = p5sound.audiocontext.currentTime;
this.bufferSourceNodes[i].stop(now);
}
}
// set play mode to effect future playback
if (s === 'restart' || s === 'sustain' || s === 'untildone') {
this.mode = s;
} else {
throw 'Invalid play mode. Must be either "restart" or "sustain"';
}
}
/**
* Pauses a file that is currently playing. If the file is not
* playing, then nothing will happen.
*
* After pausing, .play() will resume from the paused
* position.
* If p5.SoundFile had been set to loop before it was paused,
* it will continue to loop after it is unpaused with .play().
*
* @method pause
* @for p5.SoundFile
* @param {Number} [startTime] (optional) schedule event to occur
* seconds from now
* @example
* <div><code>
* let soundFile;
* function preload() {
* soundFormats('ogg', 'mp3');
* soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');
* }
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(canvasPressed);
* background(220);
* text('tap to play, release to pause', 10, 20, width - 20);
* }
* function canvasPressed() {
* soundFile.loop();
* background(0, 200, 50);
* }
* function mouseReleased() {
* soundFile.pause();
* background(220);
* }
* </code>
* </div>
*/
pause(startTime) {
var now = p5sound.audiocontext.currentTime;
var time = startTime || 0;
var pTime = time + now;
if (this.isPlaying() && this.buffer && this.bufferSourceNode) {
this._paused = true;
this._playing = false;
this.pauseTime = this.currentTime();
this.bufferSourceNode.stop(pTime);
this._counterNode.stop(pTime);
this._pauseTime = this.currentTime();
// TO DO: make sure play() still starts from orig start position
} else {
this._pauseTime = 0;
}
}
/**
* Loop the p5.SoundFile. Accepts optional parameters to set the
* playback rate, playback volume, loopStart, loopEnd.
*
* @method loop
* @for p5.SoundFile
* @param {Number} [startTime] (optional) schedule event to occur
* seconds from now
* @param {Number} [rate] (optional) playback rate
* @param {Number} [amp] (optional) playback volume
* @param {Number} [cueLoopStart] (optional) startTime in seconds
* @param {Number} [duration] (optional) loop duration in seconds
* @example
* <div><code>
* let soundFile;
* let loopStart = 0.5;
* let loopDuration = 0.2;
* function preload() {
* soundFormats('ogg', 'mp3');
* soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');
* }
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(canvasPressed);
* background(220);
* text('tap to play, release to pause', 10, 20, width - 20);
* }
* function canvasPressed() {
* soundFile.loop();
* background(0, 200, 50);
* }
* function mouseReleased() {
* soundFile.pause();
* background(220);
* }
* </code>
* </div>
*/
loop(startTime, rate, amp, loopStart, duration) {
this._looping = true;
this.play(startTime, rate, amp, loopStart, duration);
}
/**
* Set a p5.SoundFile's looping flag to true or false. If the sound
* is currently playing, this change will take effect when it
* reaches the end of the current playback.
*
* @method setLoop
* @for p5.SoundFile
* @param {Boolean} Boolean set looping to true or false
*/
setLoop(bool) {
if (bool === true) {
this._looping = true;
} else if (bool === false) {
this._looping = false;
} else {
throw 'Error: setLoop accepts either true or false';
}
if (this.bufferSourceNode) {
this.bufferSourceNode.loop = this._looping;
this._counterNode.loop = this._looping;
}
}
/**
* Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.
*
* @method isLooping
* @for p5.SoundFile
* @return {Boolean}
*/
isLooping() {
if (!this.bufferSourceNode) {
return false;
}
if (this._looping === true && this.isPlaying() === true) {
return true;
}
return false;
}
/**
* Returns true if a p5.SoundFile is playing, false if not (i.e.
* paused or stopped).
*
* @method isPlaying
* @for p5.SoundFile
* @return {Boolean}
*/
isPlaying() {
return this._playing;
}
/**
* Returns true if a p5.SoundFile is paused, false if not (i.e.
* playing or stopped).
*
* @method isPaused
* @for p5.SoundFile
* @return {Boolean}
*/
isPaused() {
return this._paused;
}
/**
* Stop soundfile playback.
*
* @method stop
* @for p5.SoundFile
* @param {Number} [startTime] (optional) schedule event to occur
* in seconds from now
*/
stop(timeFromNow) {
var time = timeFromNow || 0;
if (this.mode === 'sustain' || this.mode === 'untildone') {
this.stopAll(time);
this._playing = false;
this.pauseTime = 0;
this._paused = false;
} else if (this.buffer && this.bufferSourceNode) {
var now = p5sound.audiocontext.currentTime;
this.pauseTime = 0;
this.bufferSourceNode.stop(now + time);
this._counterNode.stop(now + time);
this._playing = false;
this._paused = false;
}
}
/**
* Stop playback on all of this soundfile's sources.
* @private
*/
stopAll(_time) {
var now = p5sound.audiocontext.currentTime;
var time = _time || 0;
if (this.buffer && this.bufferSourceNode) {
for (var i in this.bufferSourceNodes) {
const bufferSourceNode = this.bufferSourceNodes[i];
if (bufferSourceNode) {
try {
bufferSourceNode.stop(now + time);
} catch (e) {
// this was throwing errors only on Safari
}
}
}
this._counterNode.stop(now + time);
}
}
/**
* It returns the volume of a sound, which is a measure
* of how loud or quiet the sound is.
*
* @method getVolume
* @for p5.SoundFile
* @return {Number}
*/
getVolume() {
return this.output.gain.value;
}
/**
* Set the stereo panning of a p5.sound object to
* a floating point number between -1.0 (left) and 1.0 (right).
* Default is 0.0 (center).
*
* @method pan
* @for p5.SoundFile
* @param {Number} panValue Set the stereo panner
* @param {Number} [timeFromNow] schedule this event to happen
* seconds from now
* @example
* <div><code>
* let ballX = 0;
* let soundFile;
*
* function preload() {
* soundFormats('ogg', 'mp3');
* soundFile = loadSound('assets/beatbox.mp3');
* }
*
* function draw() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(canvasPressed);
* background(220);
* ballX = constrain(mouseX, 0, width);
* ellipse(ballX, height/2, 20, 20);
* }
*
* function canvasPressed(){
* // map the ball's x location to a panning degree
* // between -1.0 (left) and 1.0 (right)
* let panning = map(ballX, 0., width,-1.0, 1.0);
* soundFile.pan(panning);
* soundFile.play();
* }
* </div></code>
*/
pan(pval, tFromNow) {
this.panner.pan(pval, tFromNow);
}
/**
* Returns the current stereo pan position (-1.0 to 1.0)
*
* @method getPan
* @for p5.SoundFile
* @return {Number} Returns the stereo pan setting of the Oscillator
* as a number between -1.0 (left) and 1.0 (right).
* 0.0 is center and default.
*/
getPan() {
return this.panner.getPan();
}
/**
* Set the playback rate of a sound file. Will change the speed and the pitch.
* Values less than zero will reverse the audio buffer.
*
* @method rate
* @for p5.SoundFile
* @param {Number} [playbackRate] Set the playback rate. 1.0 is normal,
* .5 is half-speed, 2.0 is twice as fast.
* Values less than zero play backwards.
* @example
* <div><code>
* let mySound;
*
* function preload() {
* mySound = loadSound('assets/Damscray_DancingTiger.mp3');
* }
*
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(canvasPressed);
* }
* function canvasPressed() {
* mySound.loop();
* }
* function mouseReleased() {
* mySound.pause();
* }
* function draw() {
* background(220);
*
* // Set the rate to a range between 0.1 and 4
* // Changing the rate also alters the pitch
* let playbackRate = map(mouseY, 0.1, height, 2, 0);
* playbackRate = constrain(playbackRate, 0.01, 4);
* mySound.rate(playbackRate);
*
* line(0, mouseY, width, mouseY);
* text('rate: ' + round(playbackRate * 100) + '%', 10, 20);
* }
*
* </code>
* </div>
*
*/
rate(playbackRate) {
var reverse = false;
if (typeof playbackRate === 'undefined') {
return this.playbackRate;
}
this.playbackRate = playbackRate;
if (playbackRate === 0) {
playbackRate = 0.0000000000001;
} else if (playbackRate < 0 && !this.reversed) {
playbackRate = Math.abs(playbackRate);
reverse = true;
} else if (playbackRate > 0 && this.reversed) {
reverse = true;
}
if (this.bufferSourceNode) {
var now = p5sound.audiocontext.currentTime;
this.bufferSourceNode.playbackRate.cancelScheduledValues(now);
this.bufferSourceNode.playbackRate.linearRampToValueAtTime(
Math.abs(playbackRate),
now
);
this._counterNode.playbackRate.cancelScheduledValues(now);
this._counterNode.playbackRate.linearRampToValueAtTime(
Math.abs(playbackRate),
now
);
}
if (reverse) {
this.reverseBuffer();
}
return this.playbackRate;
}
/**
* Pitch of a sound file can be changed by providing a MIDI note number.
* It will change the pitch and also the speed.
* If the input note is 60 (middle C), then frequency and speed is normal.
* If we increase the note input, then frequency and speed increases,
* and if we decrease the note input, then frequency and speed decreases.
*
* @method setPitch
* @for p5.SoundFile
* @param {Number} pitchRate If the MIDI note is increased, then both the
* frequency of the sound and its playback speed
* will increase as a result.
* @example
* <div><code>
* let sound, sRate, midiVal;
* let midiNotes = [60, 64, 67, 72];
* let noteIndex = 0;
*
* function preload() {
* sound = loadSound('assets/beat.mp3');
* }
*
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mousePressed(startSound);
* }
*
* function draw() {
* background(220);
* sRate = sound.rate();
* text('tap to play', 10, 20);
* if (midiVal) {
* text('MIDI: ' + midiVal, 10, 40);
* text('Rate: ' + sRate, 10, 60);
* }
* }
*
* function startSound() {
* if (sound.isPlaying()) {
* sound.stop();
* }
* sound.play();
* midiVal = midiNotes[noteIndex % midiNotes.length];
* sound.setPitch(midiVal);
*
* noteIndex++;
* }
* </code></div>
*/
setPitch(num) {
var newPlaybackRate = midiToFreq(num) / midiToFreq(60);
this.rate(newPlaybackRate);
}
/**
* Returns the current pitch of a sound file as a MIDI note.
*
* @method getPitch
* @for p5.SoundFile
* @return {Number} Current pitch of the SoundFile. The default note is assumed to
* be 60 (middle C).
*
*/
getPitch() {
var freqValue = this.rate() * midiToFreq(60);
return freqToMidi(freqValue);
}
/**
* Returns the current playback rate of a sound file.
*
* @method getPlaybackRate
* @for p5.SoundFile
* @return {Number} Current playback rate of the SoundFile.
*
*/
getPlaybackRate() {
return this.playbackRate;
}
/**
* Multiply the output volume (amplitude) of a sound file
* between 0.0 (silence) and 1.0 (full volume).
* 1.0 is the maximum amplitude of a digital sound, so multiplying
* by greater than 1.0 may cause digital distortion. To
* fade, provide a <code>rampTime</code> parameter. For more
* complex fades, see the Envelope class.
*
* Alternately, you can pass in a signal source such as an
* oscillator to modulate the amplitude with an audio signal.
*
* @method setVolume
* @for p5.SoundFile
* @param {Number|Object} volume Volume (amplitude) between 0.0
* and 1.0 or modulating signal/oscillator
* @param {Number} [rampTime] Fade for t seconds
* @param {Number} [timeFromNow] Schedule this event to happen at
* t seconds in the future
*/
setVolume(vol, _rampTime, _tFromNow) {
if (typeof vol === 'number') {
var rampTime = _rampTime || 0;
var tFromNow = _tFromNow || 0;
var now = p5sound.audiocontext.currentTime;
var currentVol = this.output.gain.value;
this.output.gain.cancelScheduledValues(now + tFromNow);
this.output.gain.linearRampToValueAtTime(currentVol, now + tFromNow);
this.output.gain.linearRampToValueAtTime(vol, now + tFromNow + rampTime);