Skip to content

Commit 2ee8cb1

Browse files
committed
feat: Wrapper around the AudioWorkletNode
1 parent 23ca0f9 commit 2ee8cb1

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Tone/core/context/ToneAudioWorklet.ts

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { ToneAudioNode, ToneAudioNodeOptions } from "./ToneAudioNode";
2+
3+
export type ToneAudioWorkletOptions = ToneAudioNodeOptions;
4+
5+
export abstract class ToneAudioWorklet<Options extends ToneAudioWorkletOptions> extends ToneAudioNode<Options> {
6+
7+
readonly name: string = "ToneAudioWorklet";
8+
9+
/**
10+
* The processing node
11+
*/
12+
protected _worklet!: AudioWorkletNode;
13+
14+
/**
15+
* The constructor options for the node
16+
*/
17+
protected workletOptions: Partial<AudioWorkletNodeOptions> = {};
18+
19+
/**
20+
* The code which is run in the worklet
21+
*/
22+
protected abstract _audioWorklet(): string;
23+
24+
/**
25+
* Get the name of the audio worklet
26+
*/
27+
protected abstract _audioWorkletName(): string;
28+
29+
/**
30+
* Invoked when the module is loaded and the node is created
31+
*/
32+
protected abstract onReady(node: AudioWorkletNode): void;
33+
34+
constructor(options: Options) {
35+
super(options);
36+
37+
const blobUrl = URL.createObjectURL(new Blob([this._audioWorklet()], { type: "text/javascript" }));
38+
const name = this._audioWorkletName();
39+
40+
// Register the processor
41+
this.context.addAudioWorkletModule(blobUrl, name).then(() => {
42+
// create the worklet when it's read
43+
if (!this.disposed) {
44+
this._worklet = this.context.createAudioWorkletNode(name, this.workletOptions);
45+
this._worklet.onprocessorerror = e => {
46+
console.log(e);
47+
// @ts-ignore
48+
throw e.error;
49+
};
50+
this.onReady(this._worklet);
51+
}
52+
});
53+
}
54+
55+
dispose(): this {
56+
super.dispose();
57+
if (this._worklet) {
58+
this._worklet.disconnect();
59+
}
60+
return this;
61+
}
62+
63+
}

0 commit comments

Comments
 (0)