-
Notifications
You must be signed in to change notification settings - Fork 8
/
bundle.js
1471 lines (1267 loc) · 43.1 KB
/
bundle.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
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var resampler = require('./lib/resampler.js');
var dragDrop = require('drag-drop');
window.addEventListener('load', function(){
// dom elements
var fSelectOption = document.getElementById('freqSelect');
var messageBox = document.getElementById('message');
var input = document.getElementById('input');
var note = document.getElementById('note');
var spinner = document.getElementById('spinner');
//monkeypatch
var ddEventListeners = {};
var dropzone = document.querySelector('#dropzone');
var dEL = dropzone.addEventListener.bind(dropzone);
dropzone.addEventListener = function(event, callback, flag){
ddEventListeners[event] = callback;
dEL(event,callback,flag);
};
var disableDragDrop = function(elem) {
elem.removeEventListener ('dragenter', ddEventListeners.dragenter);
elem.removeEventListener('dragover', ddEventListeners.dragover);
elem.removeEventListener('drop', ddEventListeners.drop);
};
dragDrop('#dropzone', resampleDraggedFiles);
messageBox.addEventListener('click', function (){
input.click();
});
input.addEventListener('change', function(evt){
var chosenFile = evt.target.files[0];
if (chosenFile){
var chosenSampleRate = parseInt(fSelectOption.selectedOptions[0].value);
console.log(chosenFile,chosenSampleRate);
resampleFile(chosenFile,chosenSampleRate);
}
});
function resampleDraggedFiles(files){
var chosenFile = files[0] || files;
var chosenSampleRate = parseInt(fSelectOption.selectedOptions[0].value);
console.log(chosenFile,chosenSampleRate);
resampleFile(chosenFile,chosenSampleRate);
}
function resampleFile (file, targetSampleRate){
// note.messageBox.
note.style.display = "none";
spinner.style.display = "inherit";
input.disabled = true;
disableDragDrop(dropzone);
resampler(file, targetSampleRate, function(event){
event.getFile(function(fileEvent){
console.log(fileEvent);
spinner.style.display = "none";
note.style.display = "inherit";
input.disabled = false;
dragDrop('#dropzone');
var a = document.createElement("a");
document.body.appendChild(a);
a.style.display = "none";
a.href = fileEvent;
var fileExt = file.name.split('.').pop();
var fileName = file.name.substr(0, file.name.length-fileExt.length-1);
a.download = fileName + "_resampled."+ fileExt;
a.click();
window.URL.revokeObjectURL(fileEvent);
document.body.removeChild(a);
});
});
}
});
},{"./lib/resampler.js":2,"drag-drop":3}],2:[function(require,module,exports){
"use strict";
var WebAudioLoader = require('webaudioloader');
var WavEncoder = require("wav-encoder");
// WebAudio Shim.
window.OfflineAudioContext = window.OfflineAudioContext || window.webkitOfflineAudioContext;
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var wal = new WebAudioLoader({
context: audioContext,
cache: false
});
function resampler(input, targetSampleRate, oncomplete) {
if (!input && !targetSampleRate) {
return returnError('Error: First argument should be either a File, URL or AudioBuffer');
}
var inputType = Object.prototype.toString.call(input);
if (inputType !== '[object String]' &&
inputType !== '[object File]' &&
inputType !== '[object AudioBuffer]' &&
inputType !== '[object Object]') {
return returnError('Error: First argument should be either a File, URL or AudioBuffer');
}
if (typeof targetSampleRate !== 'number' ||
targetSampleRate > 192000 || targetSampleRate < 3000) {
return returnError('Error: Second argument should be a numeric sample rate between 3000 and 192000');
}
if (inputType === '[object String]' || inputType === '[object File]') {
console.log('Loading/decoding input', input);
wal.load(input, {
onload: function(err, audioBuffer) {
if (err) {
return returnError(err);
}
resampleAudioBuffer(audioBuffer);
}
});
} else if (inputType === '[object AudioBuffer]') {
resampleAudioBuffer(input);
} else if (inputType === '[object Object]' && input.leftBuffer && input.sampleRate) {
var numCh_ = input.rightBuffer ? 2 : 1;
var audioBuffer_ = audioContext.createBuffer(numCh_, input.leftBuffer.length, input.sampleRate);
resampleAudioBuffer(audioBuffer_);
} else {
return returnError('Error: Unknown input type');
}
function returnError(errMsg) {
console.error(errMsg);
if (typeof oncomplete === 'function') {
oncomplete(new Error(errMsg));
}
return;
}
function resampleAudioBuffer(audioBuffer) {
var numCh_ = audioBuffer.numberOfChannels;
var numFrames_ = audioBuffer.length * targetSampleRate / audioBuffer.sampleRate;
var offlineContext_ = new OfflineAudioContext(numCh_, numFrames_, targetSampleRate);
var bufferSource_ = offlineContext_.createBufferSource();
bufferSource_.buffer = audioBuffer;
offlineContext_.oncomplete = function(event) {
var resampeledBuffer = event.renderedBuffer;
console.log('Done Rendering');
if (typeof oncomplete === 'function') {
oncomplete({
getAudioBuffer: function() {
return resampeledBuffer;
},
getFile: function(fileCallback) {
var audioData = {
sampleRate: resampeledBuffer.sampleRate,
channelData: []
};
for (var i = 0; i < resampeledBuffer.numberOfChannels; i++) {
audioData.channelData[i] = resampeledBuffer.getChannelData(i);
}
WavEncoder.encode(audioData).then(function(buffer) {
var blob = new Blob([buffer], {
type: "audio/wav"
});
fileCallback(URL.createObjectURL(blob));
});
}
});
}
};
console.log('Starting Offline Rendering');
bufferSource_.connect(offlineContext_.destination);
bufferSource_.start(0);
offlineContext_.startRendering();
}
}
module.exports = resampler;
},{"wav-encoder":9,"webaudioloader":12}],3:[function(require,module,exports){
module.exports = DragDrop
var throttle = require('lodash.throttle')
function DragDrop (elem, cb) {
if (typeof elem === 'string') elem = document.querySelector(elem)
elem.addEventListener('dragenter', killEvent, false)
elem.addEventListener('dragover', makeOnDragOver(elem), false)
elem.addEventListener('drop', onDrop.bind(undefined, elem, cb), false)
}
function killEvent (e) {
e.stopPropagation()
e.preventDefault()
return false
}
function makeOnDragOver (elem) {
var fn = throttle(function () {
elem.classList.add('drag')
if (elem.timeout) clearTimeout(elem.timeout)
elem.timeout = setTimeout(function () {
elem.classList.remove('drag')
}, 150)
}, 100, {trailing: false})
return function (e) {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
fn()
}
}
function onDrop (elem, cb, e) {
e.stopPropagation()
e.preventDefault()
elem.classList.remove('drag')
cb(Array.prototype.slice.call(e.dataTransfer.files), { x: e.clientX, y: e.clientY })
return false
}
},{"lodash.throttle":4}],4:[function(require,module,exports){
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var debounce = require('lodash.debounce');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as an internal `_.debounce` options object by `_.throttle`. */
var debounceOptions = {
'leading': false,
'maxWait': 0,
'trailing': false
};
/**
* Creates a function that only invokes `func` at most once per every `wait`
* milliseconds. The created function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the throttled function return the result of the last
* `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to throttle.
* @param {number} wait The number of milliseconds to throttle invocations to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify invoking on the leading
* edge of the timeout.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false })
* jQuery('.interactive').on('click', throttled);
*
* // cancel a trailing throttled call
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
debounceOptions.leading = leading;
debounceOptions.maxWait = +wait;
debounceOptions.trailing = trailing;
return debounce(func, wait, debounceOptions);
}
/**
* Checks if `value` is the language type of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type == 'function' || (value && type == 'object') || false;
}
module.exports = throttle;
},{"lodash.debounce":5}],5:[function(require,module,exports){
/**
* lodash 3.0.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var isNative = require('lodash.isnative');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeNow = isNative(nativeNow = Date.now) && nativeNow;
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
/**
* Creates a function that delays invoking `func` until after `wait` milliseconds
* have elapsed since the last time it was invoked. The created function comes
* with a `cancel` method to cancel delayed invocations. Provide an options
* object to indicate that `func` should be invoked on the leading and/or
* trailing edge of the `wait` timeout. Subsequent calls to the debounced
* function return the result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it is invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : (+wait || 0);
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
/**
* Checks if `value` is the language type of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type == 'function' || (value && type == 'object') || false;
}
module.exports = debounce;
},{"lodash.isnative":6}],6:[function(require,module,exports){
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used to detect host constructors (Safari > 5). */
var reHostCtor = /^\[object .+?Constructor\]$/;
/**
* Used to match `RegExp` special characters.
* See this [article on `RegExp` characters](http://www.regular-expressions.info/characters.html#special)
* for more details.
*/
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
/**
* Converts `value` to a string if it is not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
if (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return (value && typeof value == 'object') || false;
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reNative = RegExp('^' +
escapeRegExp(objToString)
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (objToString.call(value) == funcTag) {
return reNative.test(fnToString.call(value));
}
return (isObjectLike(value) && reHostCtor.test(value)) || false;
}
/**
* Escapes the `RegExp` special characters "\", "^", "$", ".", "|", "?", "*",
* "+", "(", ")", "[", "]", "{" and "}" in `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
module.exports = isNative;
},{}],7:[function(require,module,exports){
"use strict";
/* jshint esnext: false */
/**
CAUTION!!!!
This file is used in WebWorker.
So, must write with ES5, not use ES6.
You need attention not to be traspiled by babel.
*/
var self = {};
function encoder() {
self.onmessage = function (e) {
switch (e.data.type) {
case "encode":
self.encode(e.data.audioData, e.data.format).then(function (buffer) {
var data = {
type: "encoded",
callbackId: e.data.callbackId,
buffer: buffer
};
self.postMessage(data, [buffer]);
}, function (err) {
var data = {
type: "error",
callbackId: e.data.callbackId,
message: err.message
};
self.postMessage(data);
});
break;
}
};
self.encode = function (audioData, format) {
format.floatingPoint = !!format.floatingPoint;
format.bitDepth = format.bitDepth | 0 || 16;
return new Promise(function (resolve) {
var numberOfChannels = audioData.numberOfChannels;
var sampleRate = audioData.sampleRate;
var bytes = format.bitDepth >> 3;
var length = audioData.length * numberOfChannels * bytes;
var writer = new BufferWriter(44 + length);
writer.writeString("RIFF"); // RIFF header
writer.writeUint32(writer.length - 8); // file length
writer.writeString("WAVE"); // RIFF Type
writer.writeString("fmt "); // format chunk identifier
writer.writeUint32(16); // format chunk length
writer.writeUint16(format.floatingPoint ? 3 : 1); // format (PCM)
writer.writeUint16(numberOfChannels); // number of channels
writer.writeUint32(sampleRate); // sample rate
writer.writeUint32(sampleRate * numberOfChannels * bytes); // byte rate
writer.writeUint16(numberOfChannels * bytes); // block size
writer.writeUint16(format.bitDepth); // bits per sample
writer.writeString("data"); // data chunk identifier
writer.writeUint32(length); // data chunk length
var channelData = audioData.buffers.map(function (buffer) {
return new Float32Array(buffer);
});
writer.writePCM(channelData, format);
resolve(writer.toArrayBuffer());
});
};
function BufferWriter(length) {
this.buffer = new ArrayBuffer(length);
this.view = new DataView(this.buffer);
this.length = length;
this.pos = 0;
}
BufferWriter.prototype.writeUint8 = function (data) {
this.view.setUint8(this.pos, data);
this.pos += 1;
};
BufferWriter.prototype.writeUint16 = function (data) {
this.view.setUint16(this.pos, data, true);
this.pos += 2;
};
BufferWriter.prototype.writeUint32 = function (data) {
this.view.setUint32(this.pos, data, true);
this.pos += 4;
};
BufferWriter.prototype.writeString = function (data) {
for (var i = 0; i < data.length; i++) {
this.writeUint8(data.charCodeAt(i));
}
};
BufferWriter.prototype.writePCM8 = function (x) {
x = Math.max(-128, Math.min(x * 128, 127)) | 0;
this.view.setInt8(this.pos, x);
this.pos += 1;
};
BufferWriter.prototype.writePCM16 = function (x) {
x = Math.max(-32768, Math.min(x * 32768, 32767)) | 0;
this.view.setInt16(this.pos, x, true);
this.pos += 2;
};
BufferWriter.prototype.writePCM24 = function (x) {
x = Math.max(-8388608, Math.min(x * 8388608, 8388607)) | 0;
this.view.setUint8(this.pos + 0, x >> 0 & 255);
this.view.setUint8(this.pos + 1, x >> 8 & 255);
this.view.setUint8(this.pos + 2, x >> 16 & 255);
this.pos += 3;
};
BufferWriter.prototype.writePCM32 = function (x) {
x = Math.max(-2147483648, Math.min(x * 2147483648, 2147483647)) | 0;
this.view.setInt32(this.pos, x, true);
this.pos += 4;
};
BufferWriter.prototype.writePCM32F = function (x) {
this.view.setFloat32(this.pos, x, true);
this.pos += 4;
};
BufferWriter.prototype.writePCM64F = function (x) {
this.view.setFloat64(this.pos, x, true);
this.pos += 8;
};
BufferWriter.prototype.writePCM = function (channelData, format) {
var length = channelData[0].length;
var numberOfChannels = channelData.length;
var method = "writePCM" + format.bitDepth;
if (format.floatingPoint) {
method += "F";
}
if (!this[method]) {
throw new Error("not suppoerted bit depth " + format.bitDepth);
}
for (var i = 0; i < length; i++) {
for (var ch = 0; ch < numberOfChannels; ch++) {
this[method](channelData[ch][i]);
}
}
};
BufferWriter.prototype.toArrayBuffer = function () {
return this.buffer;
};
self.BufferWriter = BufferWriter;
}
encoder.self = encoder.util = self;
module.exports = encoder;
},{}],8:[function(require,module,exports){
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
"use stirct";
var InlineWorker = _interopRequire(require("inline-worker"));
var encoder = _interopRequire(require("./encoder-worker"));
var Encoder = (function () {
function Encoder() {
var _this = this;
var format = arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Encoder);
this.format = {
floatingPoint: !!format.floatingPoint,
bitDepth: format.bitDepth | 0 || 16 };
this._worker = new InlineWorker(encoder, encoder.self);
this._worker.onmessage = function (e) {
var callback = _this._callbacks[e.data.callbackId];
if (callback) {
if (e.data.type === "encoded") {
callback.resolve(e.data.buffer);
} else {
callback.reject(new Error(e.data.message));
}
}
_this._callbacks[e.data.callbackId] = null;
};
this._callbacks = [];
}
_createClass(Encoder, {
canProcess: {
value: function canProcess(format) {
return Encoder.canProcess(format);
}
},
encode: {
value: function encode(audioData, format) {
var _this = this;
if (format == null || typeof format !== "object") {
format = this.format;
}
return new Promise(function (resolve, reject) {
var callbackId = _this._callbacks.length;
_this._callbacks.push({ resolve: resolve, reject: reject });
var numberOfChannels = audioData.channelData.length;
var length = audioData.channelData[0].length;
var sampleRate = audioData.sampleRate;
var buffers = audioData.channelData.map(function (data) {
return data.buffer;
});
audioData = { numberOfChannels: numberOfChannels, length: length, sampleRate: sampleRate, buffers: buffers };
_this._worker.postMessage({
type: "encode", audioData: audioData, format: format, callbackId: callbackId
}, audioData.buffers);
});
}
}
}, {
canProcess: {
value: function canProcess(format) {
if (format && (format === "wav" || format.type === "wav")) {
return "maybe";
}
return "";
}
},
encode: {
value: function encode(audioData, format) {
return new Encoder(format).encode(audioData);
}
}
});
return Encoder;
})();
module.exports = Encoder;
},{"./encoder-worker":7,"inline-worker":10}],9:[function(require,module,exports){
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var Encoder = _interopRequire(require("./encoder"));
module.exports = Encoder;
},{"./encoder":8}],10:[function(require,module,exports){
"use strict";
module.exports = require("./inline-worker");
},{"./inline-worker":11}],11:[function(require,module,exports){
(function (global){
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var WORKER_ENABLED = !!(global === global.window && global.URL && global.Blob && global.Worker);
var InlineWorker = (function () {
function InlineWorker(func, self) {
var _this = this;
_classCallCheck(this, InlineWorker);
if (WORKER_ENABLED) {
var functionBody = func.toString().trim().match(/^function\s*\w*\s*\([\w\s,]*\)\s*{([\w\W]*?)}$/)[1];
var url = global.URL.createObjectURL(new global.Blob([functionBody], { type: "text/javascript" }));