Skip to content

Commit

Permalink
feat(pcm): add a stop method
Browse files Browse the repository at this point in the history
  • Loading branch information
yume-chan committed Dec 4, 2023
1 parent 14abce4 commit 91d8c16
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions libraries/pcm-player/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export abstract class PcmPlayer<T> {
#channelCount: number;
#worklet: AudioWorkletNode | undefined;
#buffers: T[] = [];
#stopped = false;

constructor(sampleRate: number, channelCount: number) {
this.#context = new AudioContext({
Expand All @@ -17,6 +18,10 @@ export abstract class PcmPlayer<T> {
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;
Expand All @@ -30,6 +35,10 @@ export abstract class PcmPlayer<T> {
new URL("./worker.js", import.meta.url),
);

if (this.#stopped) {
return;
}

this.#worklet = new AudioWorkletNode(this.#context, this.sourceName, {
numberOfInputs: 0,
numberOfOutputs: 1,
Expand All @@ -44,6 +53,11 @@ export abstract class PcmPlayer<T> {
}

async stop() {
if (this.#stopped) {
return;
}
this.#stopped = true;

this.#worklet?.disconnect();
this.#worklet = undefined;

Expand Down

0 comments on commit 91d8c16

Please sign in to comment.