-
Notifications
You must be signed in to change notification settings - Fork 980
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Wrapper around the AudioWorkletNode
- Loading branch information
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { ToneAudioNode, ToneAudioNodeOptions } from "./ToneAudioNode"; | ||
|
||
export type ToneAudioWorkletOptions = ToneAudioNodeOptions; | ||
|
||
export abstract class ToneAudioWorklet<Options extends ToneAudioWorkletOptions> extends ToneAudioNode<Options> { | ||
|
||
readonly name: string = "ToneAudioWorklet"; | ||
|
||
/** | ||
* The processing node | ||
*/ | ||
protected _worklet!: AudioWorkletNode; | ||
|
||
/** | ||
* The constructor options for the node | ||
*/ | ||
protected workletOptions: Partial<AudioWorkletNodeOptions> = {}; | ||
|
||
/** | ||
* The code which is run in the worklet | ||
*/ | ||
protected abstract _audioWorklet(): string; | ||
|
||
/** | ||
* Get the name of the audio worklet | ||
*/ | ||
protected abstract _audioWorkletName(): string; | ||
|
||
/** | ||
* Invoked when the module is loaded and the node is created | ||
*/ | ||
protected abstract onReady(node: AudioWorkletNode): void; | ||
|
||
constructor(options: Options) { | ||
super(options); | ||
|
||
const blobUrl = URL.createObjectURL(new Blob([this._audioWorklet()], { type: "text/javascript" })); | ||
const name = this._audioWorkletName(); | ||
|
||
// Register the processor | ||
this.context.addAudioWorkletModule(blobUrl, name).then(() => { | ||
// create the worklet when it's read | ||
if (!this.disposed) { | ||
this._worklet = this.context.createAudioWorkletNode(name, this.workletOptions); | ||
this._worklet.onprocessorerror = e => { | ||
console.log(e); | ||
// @ts-ignore | ||
throw e.error; | ||
}; | ||
this.onReady(this._worklet); | ||
} | ||
}); | ||
} | ||
|
||
dispose(): this { | ||
super.dispose(); | ||
if (this._worklet) { | ||
this._worklet.disconnect(); | ||
} | ||
return this; | ||
} | ||
|
||
} |