/
index.ts
612 lines (500 loc) · 18.2 KB
/
index.ts
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
import type { SoundModuleParams, Module, ModuleName } from '../SoundModule';
import type { Analyser } from '../SoundModule/Analyser';
import type { Recorder } from '../SoundModule/Recorder';
import type { Autopanner } from '../SoundModule/Effectors/Autopanner';
import type { BitCrusher } from '../SoundModule/Effectors/BitCrusher';
import type { Chorus } from '../SoundModule/Effectors/Chorus';
import type { Compressor } from '../SoundModule/Effectors/Compressor';
import type { Delay } from '../SoundModule/Effectors/Delay';
import type { EnvelopeGenerator } from '../SoundModule/Effectors/EnvelopeGenerator';
import type { Equalizer } from '../SoundModule/Effectors/Equalizer';
import type { Filter } from '../SoundModule/Effectors/Filter';
import type { Flanger } from '../SoundModule/Effectors/Flanger';
import type { Fuzz } from '../SoundModule/Effectors/Fuzz';
import type { Listener } from '../SoundModule/Effectors/Listener';
import type { NoiseGate } from '../SoundModule/Effectors/NoiseGate';
import type { NoiseSuppressor } from '../SoundModule/Effectors/NoiseSuppressor';
import type { OverDrive } from '../SoundModule/Effectors/OverDrive';
import type { Panner } from '../SoundModule/Effectors/Panner';
import type { Phaser } from '../SoundModule/Effectors/Phaser';
import type { PitchShifter } from '../SoundModule/Effectors/PitchShifter';
import type { Preamp } from '../SoundModule/Effectors/Preamp';
import type { Reverb } from '../SoundModule/Effectors/Reverb';
import type { Ringmodulator } from '../SoundModule/Effectors/Ringmodulator';
import type { Stereo } from '../SoundModule/Effectors/Stereo';
import type { Tremolo } from '../SoundModule/Effectors/Tremolo';
import type { VocalCanceler } from '../SoundModule/Effectors/VocalCanceler';
import type { Wah } from '../SoundModule/Effectors/Wah';
import { SoundModule } from '../SoundModule';
import { OneshotModuleProcessor } from './OneshotModuleProcessor';
export type OneshotErrorText = 'error' | 'timeout' | 'decode';
export type OneshotSetting = {
bufferIndex: number,
playbackRate?: number,
loop?: boolean,
loopStart?: number,
loopEnd?: number,
volume?: number
};
export type OneshotSettings = OneshotSetting[];
export type OneshotModuleParams = SoundModuleParams & {
transpose?: number
};
export { OneshotModuleProcessor };
/**
* This subclass is for playing one-shot audio
* @constructor
* @extends {SoundModule}
*/
export class OneshotModule extends SoundModule {
private sources: AudioBufferSourceNode[] = [];
private resources: string[] | AudioBuffer[] = [];
private buffers: AudioBuffer[] = [];
private volumes: GainNode[] = [];
private states: boolean[] = [];
private settings: OneshotSettings = [];
private startTime = 0;
private duration = 0;
private transpose = 0;
// If error occurs at least one, this method aborts the all of connections.
// Therefore, this flag are shared with the all of `XMLHttpRequest` instances.
private loadError = false;
/**
* @param {AudioContext} context This argument is in order to use Web Audio API.
*/
constructor(context: AudioContext) {
super(context);
this.processor = new AudioWorkletNode(context, OneshotModuleProcessor.name);
}
/**
* This method creates instances of `AudioBuffer` by Ajax.
* @property {Array<string>|Array<AudioBuffer>} resources This argument is array that contains URL or instance of `AudioBuffer` for audio resources.
* @property {OneshotSettings} settings This argument is settings (such as `playbackRate`, `loop` ... etc) each audio sources.
* @property {number} timeout This argument is timeout of Ajax. The default value is 60000 msec (1 minutes).
* @property {function} successCallback This argument is invoked on success;
* @property {function} errorCallback This argument is invoked on failure.
* @property {function} progressCallback This argument is invoked during receiving audio data.
* @property {OneshotModule} Return value is for method chain.
*/
public setup(params: {
resources: string[] | AudioBuffer[];
settings: OneshotSettings;
timeout?: number;
successCallback?(event: ProgressEvent, buffers: AudioBuffer[]): void;
errorCallback?(event: ProgressEvent | Error, textStatus: OneshotErrorText): void;
progressCallback?(event: ProgressEvent): void;
}): OneshotModule {
const { resources, settings, timeout, successCallback, errorCallback, progressCallback } = params;
for (let i = 0, len = settings.length; i < len; i++) {
this.states[i] = false;
this.volumes[i] = this.context.createGain();
this.settings[i] = settings[i];
this.envelopegenerator.setGenerator(i);
}
for (let index = 0, len = resources.length; index < len; index++) {
this.resources[index] = resources[index];
const url = this.resources[index];
if (typeof url === 'string') {
// Get instance of `AudioBuffer` from designated URL.
this.load({ url, index, timeout, successCallback, errorCallback, progressCallback });
} else {
this.buffers[index] = url;
}
}
return this;
}
/**
* This method schedules playing audio.
* @param {number} startTime This argument is start time. The default value is 0.
* @param {number} duration This argument is duration. The default value is 0.
* @return {OneshotModule} Return value is for method chain.
*/
public ready(startTime?: number, duration?: number): OneshotModule {
this.startTime = startTime ?? 0;
this.duration = duration ?? 0;
this.envelopegenerator.clear(false);
return this;
}
/**
* This method starts one-shot audio.
* @param {Array<number>} indexes This argument selects instance of `AudioBufferSourceNode`.
* @return {OneshotModule} Return value is for method chain.
*/
public start(indexes: number[]): OneshotModule {
const startTime = this.context.currentTime + this.startTime;
if (!this.mixed) {
this.envelopegenerator.clear(false);
// AudioWorkletNode (Mix one-shots) -> ... -> AudioDestinationNode (Output)
this.connect(this.processor);
}
for (const index of indexes) {
if ((index < 0) || (index >= this.settings.length)) {
continue;
}
const { bufferIndex, playbackRate, loop, loopStart, loopEnd, volume } = this.settings[index];
// The following code is unnecessary, because `AudioBufferSourceNode` is the target of garbage collection in case of no references and no sound
// (If there is this code, application cannot repeat hits).
// if (this.sources[index]) {
// this.sources[index].stop(this.context.currentTime);
// this.sources[index].disconnect(0);
// }
const source = this.context.createBufferSource();
source.buffer = this.buffers[bufferIndex];
source.playbackRate.value = playbackRate ?? 1;
source.detune.value = this.transpose * 100;
source.loop = loop ?? false;
source.loopStart = loopStart ?? 0;
source.loopEnd = loopEnd ?? source.buffer.duration;
this.volumes[index].gain.value = volume ?? 1;
// AudioBufferSourceNode (Input) -> GainNode (Envelope Generator) -> GainNode (Volume) -> AudioWorkletNode (Mix one-shots)
this.envelopegenerator.ready(index, source, this.volumes[index]);
this.volumes[index].connect(this.processor);
if (source.loop) {
source.start(startTime, (startTime + source.loopStart), (source.loopEnd - startTime));
} else {
source.start(startTime);
}
this.sources[index] = source;
this.states[index] = true;
}
// Attack -> Decay -> Sustain
this.envelopegenerator.start(startTime);
this.on(startTime);
if (!this.runningAnalyser) {
this.analyser.start('time');
this.analyser.start('fft');
this.runningAnalyser = true;
}
return this;
}
/**
* This method stops one-shot audio.
* @param {Array<number>} indexes This argument selects instance of `AudioBufferSourceNode`.
* @return {OneshotModule} Return value is for method chain.
*/
public stop(indexes: number[]): OneshotModule {
const stopTime = this.context.currentTime + this.startTime + this.duration;
indexes.forEach((index: number) => {
if (this.states[index]) {
this.sources[index].stop(stopTime);
this.states[index] = false;
}
});
// Attack or Decay or Sustain -> Release
this.envelopegenerator.stop(stopTime);
this.envelopegenerator.clear(false);
this.off(stopTime);
return this;
}
/**
* This method gets or sets parameters for one-shot module.
* This method is overloaded for type interface and type check.
* @param {keyof OneshotModuleParams|OneshotModuleParams} params This argument is string if getter. Otherwise, setter.
* @return {OneshotModuleParams[keyof OneshotModuleParams]|OneshotModule} Return value is parameter for one-shot module if getter.
* Otherwise, return value is for method chain.
*/
public param(params: 'mastervolume'): number;
public param(params: 'transpose'): number;
public param(params: OneshotModuleParams): OneshotModule;
public param(params: keyof OneshotModuleParams | OneshotModuleParams): OneshotModuleParams[keyof OneshotModuleParams] | OneshotModule {
if (typeof params === 'string') {
switch (params) {
case 'mastervolume': {
return this.mastervolume.gain.value;
}
case 'transpose': {
return this.transpose;
}
}
}
for (const [key, value] of Object.entries(params)) {
switch (key) {
case 'mastervolume': {
if (typeof value === 'number') {
this.mastervolume.gain.value = value;
}
break;
}
case 'transpose': {
if (typeof value === 'number') {
this.transpose = value;
}
break;
}
}
}
return this;
}
/**
* This method gets instance of `AudioBuffer` or array that contains the all of `AudioBuffer`s.
* This method is overloaded for type interface and type check.
* @param {number} index This argument selects instance of `AudioBuffer`.
* @return {AudioBuffer|AudioBuffer[]}
*/
public get(index: number): AudioBuffer;
public get(): AudioBuffer[];
public get(index?: number): AudioBuffer | AudioBuffer[] {
if ((typeof index === 'number') && (index >= 0) && (index < this.buffers.length)) {
return this.buffers[index];
}
return this.buffers;
}
/**
* This method resets settings.
* @param {number} index This argument selects target setting.
* @param {keyof OneshotSetting} paramName This argument is one-shot parameter name.
* @param {OneshotSetting} param This argument is one-shot parameter value.
* @return {OneshotModule} Return value is for method chain.
*/
public reset(index: number, paramName: keyof OneshotSetting, param: number | boolean): OneshotModule {
if ((index >= 0) && (index < this.settings.length)) {
switch (paramName) {
case 'bufferIndex' :
case 'playbackRate':
case 'loopStart' :
case 'loopEnd' :
case 'volume' : {
if (typeof param === 'number') {
this.settings[index][paramName] = param;
}
break;
}
case 'loop': {
if (typeof param === 'boolean') {
this.settings[index][paramName] = param;
}
break;
}
}
}
return this;
}
/**
* This method gets instance of `Module` (Analyser, Recorder, Effector ... etc).
* @param {ModuleName} moduleName This argument selects module.
* @return {Module}
*/
public module(moduleName: 'analyser'): Analyser;
public module(moduleName: 'recorder'): Recorder;
public module(moduleName: 'autopanner'): Autopanner;
public module(moduleName: 'bitcrusher'): BitCrusher;
public module(moduleName: 'chorus'): Chorus;
public module(moduleName: 'compressor'): Compressor;
public module(moduleName: 'delay'): Delay;
public module(moduleName: 'envelopegenerator'): EnvelopeGenerator;
public module(moduleName: 'equalizer'): Equalizer;
public module(moduleName: 'filter'): Filter;
public module(moduleName: 'flanger'): Flanger;
public module(moduleName: 'fuzz'): Fuzz;
public module(moduleName: 'listener'): Listener;
public module(moduleName: 'noisegate'): NoiseGate;
public module(moduleName: 'noisesuppressor'): NoiseSuppressor;
public module(moduleName: 'overdrive'): OverDrive;
public module(moduleName: 'panner'): Panner;
public module(moduleName: 'phaser'): Phaser;
public module(moduleName: 'pitchshifter'): PitchShifter;
public module(moduleName: 'preamp'): Preamp;
public module(moduleName: 'reverb'): Reverb;
public module(moduleName: 'ringmodulator'): Ringmodulator;
public module(moduleName: 'stereo'): Stereo;
public module(moduleName: 'tremolo'): Tremolo;
public module(moduleName: 'vocalcanceler'): VocalCanceler;
public module(moduleName: 'wah'): Wah;
public module(moduleName: ModuleName): Module {
switch (moduleName) {
case 'analyser': {
return this.analyser;
}
case 'recorder': {
return this.recorder;
}
case 'autopanner': {
return this.autopanner;
}
case 'bitcrusher': {
return this.bitcrusher;
}
case 'chorus': {
return this.chorus;
}
case 'compressor': {
return this.compressor;
}
case 'delay': {
return this.delay;
}
case 'envelopegenerator': {
return this.envelopegenerator;
}
case 'equalizer': {
return this.equalizer;
}
case 'filter': {
return this.filter;
}
case 'flanger': {
return this.flanger;
}
case 'fuzz': {
return this.fuzz;
}
case 'listener': {
return this.listener;
}
case 'noisegate': {
return this.noisegate;
}
case 'noisesuppressor': {
return this.noisesuppressor;
}
case 'overdrive': {
return this.overdrive;
}
case 'panner': {
return this.panner;
}
case 'phaser': {
return this.phaser;
}
case 'pitchshifter': {
return this.pitchshifter;
}
case 'preamp': {
return this.preamp;
}
case 'reverb': {
return this.reverb;
}
case 'ringmodulator': {
return this.ringmodulator;
}
case 'stereo': {
return this.stereo;
}
case 'tremolo': {
return this.tremolo;
}
case 'vocalcanceler': {
return this.vocalcanceler;
}
case 'wah': {
return this.wah;
}
}
}
/** @override */
public override on(startTime?: number): OneshotModule {
super.on(startTime);
return this;
}
/** @override */
public override off(stopTime?: number): OneshotModule {
super.off(stopTime);
return this;
}
/** @override */
public override suspend(): OneshotModule {
super.suspend();
return this;
}
/** @override */
public override mix(): OneshotModule {
super.mix();
return this;
}
/** @override */
public override demix(): OneshotModule {
super.demix();
return this;
}
/**
* This method gets one-shot module parameters as associative array.
* @return {OneshotModuleParams}
* @override
*/
public override params(): Required<OneshotModuleParams> {
const params = super.params();
return {
...params,
transpose: this.transpose
};
}
/** @override */
public override get INPUT(): AudioWorkletNode {
return this.processor;
}
/** @override */
public override get OUTPUT(): GainNode {
return this.mastervolume;
}
/**
* This method gets `ArrayBuffer` and creates instance of `AudioBuffer`.
* @property {string} url This argument is resource URL for one-shot audio.
* @property {number} index This argument is in order to assign instance of `AudioBuffer`.
* @property {number} timeout This argument is timeout of Ajax. The default value is 60000 msec (1 minutes).
* @property {function} successCallback This argument is invoked on success;
* @property {function} errorCallback This argument is invoked on failure.
* @property {function} progressCallback This argument is invoked during receiving audio data.
*/
private load(params: {
url: string;
index: number;
timeout?: number;
successCallback?(event: ProgressEvent, buffers: AudioBuffer[]): void;
errorCallback?(event: ProgressEvent | Error, textStatus: OneshotErrorText): void;
progressCallback?(event: ProgressEvent): void;
}): void {
const { url, index, timeout, successCallback, errorCallback, progressCallback } = params;
const xhr = new XMLHttpRequest();
xhr.timeout = timeout ?? 60000;
xhr.ontimeout = (event: ProgressEvent) => {
if (!this.loadError && errorCallback) {
errorCallback(event, 'timeout');
}
this.loadError = true;
};
xhr.onprogress = (event: ProgressEvent) => {
if (this.loadError) {
xhr.abort();
} else if (progressCallback) {
progressCallback(event);
}
};
xhr.onerror = (event: ProgressEvent) => {
if (!this.loadError && errorCallback) {
errorCallback(event, 'error');
}
this.loadError = true;
};
// Success
xhr.onload = (event: ProgressEvent) => {
if (xhr.status === 200) {
const arrayBuffer = xhr.response;
if (!(arrayBuffer instanceof ArrayBuffer)) {
return;
}
const decodeSuccessCallback = (buffer: AudioBuffer) => {
this.buffers[index] = buffer;
// Creating instance of `AudioBuffer` has completed ?
for (const buffer of this.buffers) {
if (buffer === undefined) {
return;
}
}
if (successCallback) {
successCallback(event, this.buffers);
}
};
const decodeErrorCallback = (error: Error) => {
if (errorCallback) {
errorCallback(error, 'decode');
}
};
this.context.decodeAudioData(arrayBuffer, decodeSuccessCallback, decodeErrorCallback);
}
};
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send(null);
}
}