From 91d8c1687f7faa403200df9796b8a4c8d19c84f7 Mon Sep 17 00:00:00 2001 From: Simon Chan <1330321+yume-chan@users.noreply.github.com> Date: Tue, 5 Dec 2023 01:49:23 +0800 Subject: [PATCH] feat(pcm): add a stop method --- libraries/pcm-player/src/index.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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;