forked from scratchfoundation/scratch-audio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdist.js
More file actions
2043 lines (1670 loc) · 63.3 KB
/
dist.js
File metadata and controls
2043 lines (1670 loc) · 63.3 KB
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
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 11);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
var microee = __webpack_require__(13);
// Implements a subset of Node's stream.Transform - in a cross-platform manner.
function Transform() {}
microee.mixin(Transform);
// The write() signature is different from Node's
// --> makes it much easier to work with objects in logs.
// One of the lessons from v1 was that it's better to target
// a good browser rather than the lowest common denominator
// internally.
// If you want to use external streams, pipe() to ./stringify.js first.
Transform.prototype.write = function(name, level, args) {
this.emit('item', name, level, args);
};
Transform.prototype.end = function() {
this.emit('end');
this.removeAllListeners();
};
Transform.prototype.pipe = function(dest) {
var s = this;
// prevent double piping
s.emit('unpipe', dest);
// tell the dest that it's being piped to
dest.emit('pipe', s);
function onItem() {
dest.write.apply(dest, Array.prototype.slice.call(arguments));
}
function onEnd() { !dest._isStdio && dest.end(); }
s.on('item', onItem);
s.on('end', onEnd);
s.when('unpipe', function(from) {
var match = (from === dest) || typeof from == 'undefined';
if(match) {
s.removeListener('item', onItem);
s.removeListener('end', onEnd);
dest.emit('unpipe');
}
return match;
});
return dest;
};
Transform.prototype.unpipe = function(from) {
this.emit('unpipe', from);
return this;
};
Transform.prototype.format = function(dest) {
throw new Error([
'Warning: .format() is deprecated in Minilog v2! Use .pipe() instead. For example:',
'var Minilog = require(\'minilog\');',
'Minilog',
' .pipe(Minilog.backends.console.formatClean)',
' .pipe(Minilog.backends.console);'].join('\n'));
};
Transform.mixin = function(dest) {
var o = Transform.prototype, k;
for (k in o) {
o.hasOwnProperty(k) && (dest.prototype[k] = o[k]);
}
};
module.exports = Transform;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var minilog = __webpack_require__(20);
minilog.enable();
module.exports = minilog('scratch-audioengine');
/***/ }),
/* 2 */
/***/ (function(module, exports) {
var hex = {
black: '#000',
red: '#c23621',
green: '#25bc26',
yellow: '#bbbb00',
blue: '#492ee1',
magenta: '#d338d3',
cyan: '#33bbc8',
gray: '#808080',
purple: '#708'
};
function color(fg, isInverse) {
if(isInverse) {
return 'color: #fff; background: '+hex[fg]+';';
} else {
return 'color: '+hex[fg]+';';
}
}
module.exports = color;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var window = __webpack_require__(12)
var OfflineContext = window.OfflineAudioContext || window.webkitOfflineAudioContext
var Context = window.AudioContext || window.webkitAudioContext
var cache = {}
module.exports = function getContext (options) {
if (!Context) return null
if (typeof options === 'number') {
options = {sampleRate: options}
}
var sampleRate = options && options.sampleRate
if (options && options.offline) {
if (!OfflineContext) return null
return new OfflineContext(options.channels || 2, options.length, sampleRate || 44100)
}
//cache by sampleRate, rather strong guess
var ctx = cache[sampleRate]
if (ctx) return ctx
//several versions of firefox have issues with the
//constructor argument
//see: https://bugzilla.mozilla.org/show_bug.cgi?id=1361475
try {
ctx = new Context(options)
}
catch (err) {
ctx = new Context()
}
cache[ctx.sampleRate] = cache[sampleRate] = ctx
return ctx
}
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ArrayBufferStream = __webpack_require__(10);
var log = __webpack_require__(1);
/**
* Decode wav audio files that have been compressed with the ADPCM format.
* This is necessary because, while web browsers have native decoders for many audio
* formats, ADPCM is a non-standard format used by Scratch since its early days.
* This decoder is based on code from Scratch-Flash:
* https://github.com/LLK/scratch-flash/blob/master/src/sound/WAVFile.as
*/
var ADPCMSoundDecoder = function () {
/**
* @param {AudioContext} audioContext - a webAudio context
* @constructor
*/
function ADPCMSoundDecoder(audioContext) {
_classCallCheck(this, ADPCMSoundDecoder);
this.audioContext = audioContext;
}
/**
* Data used by the decompression algorithm
* @type {Array}
*/
_createClass(ADPCMSoundDecoder, [{
key: 'decode',
/**
* Decode an ADPCM sound stored in an ArrayBuffer and return a promise
* with the decoded audio buffer.
* @param {ArrayBuffer} audioData - containing ADPCM encoded wav audio
* @return {AudioBuffer} the decoded audio buffer
*/
value: function decode(audioData) {
var _this = this;
return new Promise(function (resolve, reject) {
var stream = new ArrayBufferStream(audioData);
var riffStr = stream.readUint8String(4);
if (riffStr !== 'RIFF') {
log.warn('incorrect adpcm wav header');
reject();
}
var lengthInHeader = stream.readInt32();
if (lengthInHeader + 8 !== audioData.byteLength) {
log.warn('adpcm wav length in header: ' + lengthInHeader + ' is incorrect');
}
var wavStr = stream.readUint8String(4);
if (wavStr !== 'WAVE') {
log.warn('incorrect adpcm wav header');
reject();
}
var formatChunk = _this.extractChunk('fmt ', stream);
_this.encoding = formatChunk.readUint16();
_this.channels = formatChunk.readUint16();
_this.samplesPerSecond = formatChunk.readUint32();
_this.bytesPerSecond = formatChunk.readUint32();
_this.blockAlignment = formatChunk.readUint16();
_this.bitsPerSample = formatChunk.readUint16();
formatChunk.position += 2; // skip extra header byte count
_this.samplesPerBlock = formatChunk.readUint16();
_this.adpcmBlockSize = (_this.samplesPerBlock - 1) / 2 + 4; // block size in bytes
var samples = _this.imaDecompress(_this.extractChunk('data', stream), _this.adpcmBlockSize);
var buffer = _this.audioContext.createBuffer(1, samples.length, _this.samplesPerSecond);
// @todo optimize this? e.g. replace the divide by storing 1/32768 and multiply?
for (var i = 0; i < samples.length; i++) {
buffer.getChannelData(0)[i] = samples[i] / 32768;
}
resolve(buffer);
});
}
/**
* Extract a chunk of audio data from the stream, consisting of a set of audio data bytes
* @param {string} chunkType - the type of chunk to extract. 'data' or 'fmt' (format)
* @param {ArrayBufferStream} stream - an stream containing the audio data
* @return {ArrayBufferStream} a stream containing the desired chunk
*/
}, {
key: 'extractChunk',
value: function extractChunk(chunkType, stream) {
stream.position = 12;
while (stream.position < stream.getLength() - 8) {
var typeStr = stream.readUint8String(4);
var chunkSize = stream.readInt32();
if (typeStr === chunkType) {
var chunk = stream.extract(chunkSize);
return chunk;
}
stream.position += chunkSize;
}
}
/**
* Decompress sample data using the IMA ADPCM algorithm.
* Note: Handles only one channel, 4-bits per sample.
* @param {ArrayBufferStream} compressedData - a stream of compressed audio samples
* @param {number} blockSize - the number of bytes in the stream
* @return {Int16Array} the uncompressed audio samples
*/
}, {
key: 'imaDecompress',
value: function imaDecompress(compressedData, blockSize) {
var sample = void 0;
var step = void 0;
var code = void 0;
var delta = void 0;
var index = 0;
var lastByte = -1; // -1 indicates that there is no saved lastByte
var out = [];
// Bail and return no samples if we have no data
if (!compressedData) return out;
compressedData.position = 0;
// @todo Update this loop ported from Scratch 2.0 to use a condition or a for loop.
while (true) {
// eslint-disable-line no-constant-condition
if (compressedData.position % blockSize === 0 && lastByte < 0) {
// read block header
if (compressedData.getBytesAvailable() === 0) break;
sample = compressedData.readInt16();
index = compressedData.readUint8();
compressedData.position++; // skip extra header byte
if (index > 88) index = 88;
out.push(sample);
} else {
// read 4-bit code and compute delta from previous sample
if (lastByte < 0) {
if (compressedData.getBytesAvailable() === 0) break;
lastByte = compressedData.readUint8();
code = lastByte & 0xF;
} else {
code = lastByte >> 4 & 0xF;
lastByte = -1;
}
step = ADPCMSoundDecoder.STEP_TABLE[index];
delta = 0;
if (code & 4) delta += step;
if (code & 2) delta += step >> 1;
if (code & 1) delta += step >> 2;
delta += step >> 3;
// compute next index
index += ADPCMSoundDecoder.INDEX_TABLE[code];
if (index > 88) index = 88;
if (index < 0) index = 0;
// compute and output sample
sample += code & 8 ? -delta : delta;
if (sample > 32767) sample = 32767;
if (sample < -32768) sample = -32768;
out.push(sample);
}
}
var samples = Int16Array.from(out);
return samples;
}
}], [{
key: 'STEP_TABLE',
get: function get() {
return [7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767];
}
/**
* Data used by the decompression algorithm
* @type {Array}
*/
}, {
key: 'INDEX_TABLE',
get: function get() {
return [-1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8];
}
}]);
return ADPCMSoundDecoder;
}();
module.exports = ADPCMSoundDecoder;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var log = __webpack_require__(1);
/**
* A SoundPlayer stores an audio buffer, and plays it
*/
var SoundPlayer = function () {
/**
* @param {AudioContext} audioContext - a webAudio context
* @constructor
*/
function SoundPlayer(audioContext) {
_classCallCheck(this, SoundPlayer);
this.audioContext = audioContext;
this.outputNode = null;
this.buffer = null;
this.bufferSource = null;
this.playbackRate = 1;
this.isPlaying = false;
}
/**
* Connect the SoundPlayer to an output node
* @param {GainNode} node - an output node to connect to
*/
_createClass(SoundPlayer, [{
key: 'connect',
value: function connect(node) {
this.outputNode = node;
}
/**
* Set an audio buffer
* @param {AudioBuffer} buffer - Buffer to set
*/
}, {
key: 'setBuffer',
value: function setBuffer(buffer) {
this.buffer = buffer;
}
/**
* Set the playback rate for the sound
* @param {number} playbackRate - a ratio where 1 is normal playback, 0.5 is half speed, 2 is double speed, etc.
*/
}, {
key: 'setPlaybackRate',
value: function setPlaybackRate(playbackRate) {
this.playbackRate = playbackRate;
if (this.bufferSource && this.bufferSource.playbackRate) {
this.bufferSource.playbackRate.value = this.playbackRate;
}
}
/**
* Stop the sound
*/
}, {
key: 'stop',
value: function stop() {
if (this.bufferSource && this.isPlaying) {
this.bufferSource.stop();
}
this.isPlaying = false;
}
/**
* Start playing the sound
* The web audio framework requires a new audio buffer source node for each playback
*/
}, {
key: 'start',
value: function start() {
if (!this.buffer) {
log.warn('tried to play a sound that was not loaded yet');
return;
}
this.bufferSource = this.audioContext.createBufferSource();
this.bufferSource.buffer = this.buffer;
this.bufferSource.playbackRate.value = this.playbackRate;
this.bufferSource.connect(this.outputNode);
this.bufferSource.start();
this.isPlaying = true;
}
/**
* The sound has finished playing. This is called at the correct time even if the playback rate
* has been changed
* @return {Promise} a Promise that resolves when the sound finishes playing
*/
}, {
key: 'finished',
value: function finished() {
var _this = this;
return new Promise(function (resolve) {
_this.bufferSource.onended = function () {
_this.isPlaying = false;
resolve();
};
});
}
}]);
return SoundPlayer;
}();
module.exports = SoundPlayer;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* A pan effect, which moves the sound to the left or right between the speakers
* Effect value of -100 puts the audio entirely on the left channel,
* 0 centers it, 100 puts it on the right.
*/
var PanEffect = function () {
/**
* @param {AudioEngine} audioEngine - the audio engine.
* @constructor
*/
function PanEffect(audioEngine) {
_classCallCheck(this, PanEffect);
this.audioEngine = audioEngine;
this.audioContext = this.audioEngine.audioContext;
this.value = 0;
this.input = this.audioContext.createGain();
this.leftGain = this.audioContext.createGain();
this.rightGain = this.audioContext.createGain();
this.channelMerger = this.audioContext.createChannelMerger(2);
this.input.connect(this.leftGain);
this.input.connect(this.rightGain);
this.leftGain.connect(this.channelMerger, 0, 0);
this.rightGain.connect(this.channelMerger, 0, 1);
this.set(this.value);
}
/**
* Set the effect value
* @param {number} val - the new value to set the effect to
*/
_createClass(PanEffect, [{
key: "set",
value: function set(val) {
this.value = val;
// Map the scratch effect value (-100 to 100) to (0 to 1)
var p = (val + 100) / 200;
// Use trig functions for equal-loudness panning
// See e.g. https://docs.cycling74.com/max7/tutorials/13_panningchapter01
var leftVal = Math.cos(p * Math.PI / 2);
var rightVal = Math.sin(p * Math.PI / 2);
this.leftGain.gain.setTargetAtTime(leftVal, 0, this.audioEngine.DECAY_TIME);
this.rightGain.gain.setTargetAtTime(rightVal, 0, this.audioEngine.DECAY_TIME);
}
/**
* Connnect this effect's output to another audio node
* @param {AudioNode} node - the node to connect to
*/
}, {
key: "connect",
value: function connect(node) {
this.channelMerger.connect(node);
}
/**
* Clean up and disconnect audio nodes.
*/
}, {
key: "dispose",
value: function dispose() {
this.input.disconnect();
this.leftGain.disconnect();
this.rightGain.disconnect();
this.channelMerger.disconnect();
}
}]);
return PanEffect;
}();
module.exports = PanEffect;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* A pitch change effect, which changes the playback rate of the sound in order
* to change its pitch: reducing the playback rate lowers the pitch, increasing the rate
* raises the pitch. The duration of the sound is also changed.
*
* Changing the value of the pitch effect by 10 causes a change in pitch by 1 semitone
* (i.e. a musical half-step, such as the difference between C and C#)
* Changing the pitch effect by 120 changes the pitch by one octave (12 semitones)
*
* The value of this effect is not clamped (i.e. it is typically between -120 and 120,
* but can be set much higher or much lower, with weird and fun results).
* We should consider what extreme values to use for clamping it.
*
* Note that this effect functions differently from the other audio effects. It is
* not part of a chain of audio nodes. Instead, it provides a way to set the playback
* on one SoundPlayer or a group of them.
*/
var PitchEffect = function () {
function PitchEffect() {
_classCallCheck(this, PitchEffect);
this.value = 0; // effect value
this.ratio = 1; // the playback rate ratio
}
/**
* Set the effect value
* @param {number} val - the new value to set the effect to
* @param {object} players - a dictionary of SoundPlayer objects to apply the effect to, indexed by md5
*/
_createClass(PitchEffect, [{
key: "set",
value: function set(val, players) {
this.value = val;
this.ratio = this.getRatio(this.value);
this.updatePlayers(players);
}
/**
* Change the effect value
* @param {number} val - the value to change the effect by
* @param {object} players - a dictionary of SoundPlayer objects indexed by md5
*/
}, {
key: "changeBy",
value: function changeBy(val, players) {
this.set(this.value + val, players);
}
/**
* Compute the playback ratio for an effect value.
* The playback ratio is scaled so that a change of 10 in the effect value
* gives a change of 1 semitone in the ratio.
* @param {number} val - an effect value
* @returns {number} a playback ratio
*/
}, {
key: "getRatio",
value: function getRatio(val) {
var interval = val / 10;
// Convert the musical interval in semitones to a frequency ratio
return Math.pow(2, interval / 12);
}
/**
* Update a sound player's playback rate using the current ratio for the effect
* @param {object} player - a SoundPlayer object
*/
}, {
key: "updatePlayer",
value: function updatePlayer(player) {
player.setPlaybackRate(this.ratio);
}
/**
* Update a sound player's playback rate using the current ratio for the effect
* @param {object} players - a dictionary of SoundPlayer objects to update, indexed by md5
*/
}, {
key: "updatePlayers",
value: function updatePlayers(players) {
if (!players) return;
for (var md5 in players) {
if (players.hasOwnProperty(md5)) {
this.updatePlayer(players[md5]);
}
}
}
}]);
return PitchEffect;
}();
module.exports = PitchEffect;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @fileoverview UID generator, from Blockly.
*/
/**
* Legal characters for the unique ID.
* Should be all on a US keyboard. No XML special characters or control codes.
* Removed $ due to issue 251.
* @private
*/
var soup_ = '!#%()*+,-./:;=?@[]^_`{|}~' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
/**
* Generate a unique ID, from Blockly. This should be globally unique.
* 87 characters ^ 20 length > 128 bits (better than a UUID).
* @return {string} A globally unique ID string.
*/
var uid = function uid() {
var length = 20;
var soupLength = soup_.length;
var id = [];
for (var i = 0; i < length; i++) {
id[i] = soup_.charAt(Math.random() * soupLength);
}
return id.join('');
};
module.exports = uid;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
* StartAudioContext.js
* @author Yotam Mann
* @license http://opensource.org/licenses/MIT MIT License
* @copyright 2016 Yotam Mann
*/
(function (root, factory) {
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
} else if (typeof module === "object" && module.exports) {
module.exports = factory()
} else {
root.StartAudioContext = factory()
}
}(this, function () {
//TAP LISTENER/////////////////////////////////////////////////////////////
/**
* @class Listens for non-dragging tap ends on the given element
* @param {Element} element
* @internal
*/
var TapListener = function(element, context){
this._dragged = false
this._element = element
this._bindedMove = this._moved.bind(this)
this._bindedEnd = this._ended.bind(this, context)
element.addEventListener("touchstart", this._bindedEnd)
element.addEventListener("touchmove", this._bindedMove)
element.addEventListener("touchend", this._bindedEnd)
element.addEventListener("mouseup", this._bindedEnd)
}
/**
* drag move event
*/
TapListener.prototype._moved = function(e){
this._dragged = true
};
/**
* tap ended listener
*/
TapListener.prototype._ended = function(context){
if (!this._dragged){
startContext(context)
}
this._dragged = false
};
/**
* remove all the bound events
*/
TapListener.prototype.dispose = function(){
this._element.removeEventListener("touchstart", this._bindedEnd)
this._element.removeEventListener("touchmove", this._bindedMove)
this._element.removeEventListener("touchend", this._bindedEnd)
this._element.removeEventListener("mouseup", this._bindedEnd)
this._bindedMove = null
this._bindedEnd = null
this._element = null
};
//END TAP LISTENER/////////////////////////////////////////////////////////
/**
* Plays a silent sound and also invoke the "resume" method
* @param {AudioContext} context
* @private
*/
function startContext(context){
// this accomplishes the iOS specific requirement
var buffer = context.createBuffer(1, 1, context.sampleRate)
var source = context.createBufferSource()
source.buffer = buffer
source.connect(context.destination)
source.start(0)
// resume the audio context
if (context.resume){
context.resume()
}
}
/**
* Returns true if the audio context is started
* @param {AudioContext} context
* @return {Boolean}
* @private
*/
function isStarted(context){
return context.state === "running"
}
/**
* Invokes the callback as soon as the AudioContext
* is started
* @param {AudioContext} context
* @param {Function} callback
*/
function onStarted(context, callback){
function checkLoop(){
if (isStarted(context)){
callback()
} else {
requestAnimationFrame(checkLoop)
if (context.resume){
context.resume()
}
}
}
if (isStarted(context)){
callback()
} else {
checkLoop()
}
}
/**
* Add a tap listener to the audio context
* @param {Array|Element|String|jQuery} element
* @param {Array} tapListeners
*/
function bindTapListener(element, tapListeners, context){
if (Array.isArray(element) || (NodeList && element instanceof NodeList)){
for (var i = 0; i < element.length; i++){
bindTapListener(element[i], tapListeners, context)
}
} else if (typeof element === "string"){
bindTapListener(document.querySelectorAll(element), tapListeners, context)
} else if (element.jquery && typeof element.toArray === "function"){
bindTapListener(element.toArray(), tapListeners, context)
} else if (Element && element instanceof Element){
//if it's an element, create a TapListener
var tap = new TapListener(element, context)
tapListeners.push(tap)
}
}
/**
* @param {AudioContext} context The AudioContext to start.
* @param {Array|String|Element|jQuery=} elements For iOS, the list of elements
* to bind tap event listeners
* which will start the AudioContext. If
* no elements are given, it will bind
* to the document.body.
* @param {Function=} callback The callback to invoke when the AudioContext is started.
* @return {Promise} The promise is invoked when the AudioContext
* is started.
*/
function StartAudioContext(context, elements, callback){
//the promise is invoked when the AudioContext is started
var promise = new Promise(function(success) {
onStarted(context, success)
})
// The TapListeners bound to the elements
var tapListeners = []
// add all the tap listeners
if (!elements){
elements = document.body
}
bindTapListener(elements, tapListeners, context)
//dispose all these tap listeners when the context is started
promise.then(function(){
for (var i = 0; i < tapListeners.length; i++){
tapListeners[i].dispose()
}
tapListeners = null