diff --git a/libraries/pcm-player/src/index.ts b/libraries/pcm-player/src/index.ts index 51ee3e9b7..c617b1dbd 100644 --- a/libraries/pcm-player/src/index.ts +++ b/libraries/pcm-player/src/index.ts @@ -5,6 +5,7 @@ export abstract class PcmPlayer { #channelCount: number; #worklet: AudioWorkletNode | undefined; #buffers: T[] = []; + #stopped = false; constructor(sampleRate: number, channelCount: number) { this.#context = new AudioContext({ @@ -17,6 +18,10 @@ export abstract class PcmPlayer { protected abstract feedCore(worklet: AudioWorkletNode, source: T): void; feed(source: T) { + if (this.#stopped) { + throw new Error("PcmPlayer is stopped"); + } + if (this.#worklet === undefined) { this.#buffers.push(source); return; @@ -30,6 +35,10 @@ export abstract class PcmPlayer { new URL("./worker.js", import.meta.url), ); + if (this.#stopped) { + return; + } + this.#worklet = new AudioWorkletNode(this.#context, this.sourceName, { numberOfInputs: 0, numberOfOutputs: 1, @@ -44,6 +53,11 @@ export abstract class PcmPlayer { } async stop() { + if (this.#stopped) { + return; + } + this.#stopped = true; + this.#worklet?.disconnect(); this.#worklet = undefined;