@cartesia/cartesia-js 0.0.4-alpha.0 → 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/.turbo/turbo-build.log +64 -46
  2. package/CHANGELOG.md +6 -0
  3. package/README.md +123 -16
  4. package/dist/{chunk-XPIMIAAE.js → chunk-3FL2SNIR.js} +1 -1
  5. package/dist/chunk-3GBZUGUD.js +17 -0
  6. package/dist/chunk-4RMSIQLG.js +25 -0
  7. package/dist/chunk-BCQ63627.js +32 -0
  8. package/dist/chunk-JOHSCOLW.js +106 -0
  9. package/dist/chunk-LYPTISWL.js +75 -0
  10. package/dist/chunk-NDNN326Q.js +207 -0
  11. package/dist/chunk-WBK6LLXX.js +58 -0
  12. package/dist/chunk-WE63M7PJ.js +119 -0
  13. package/dist/{chunk-R4P7LWVZ.js → chunk-WIFMLPT5.js} +31 -6
  14. package/dist/chunk-X7SJMF2R.js +22 -0
  15. package/dist/index.cjs +391 -158
  16. package/dist/index.d.cts +7 -3
  17. package/dist/index.d.ts +7 -3
  18. package/dist/index.js +13 -6
  19. package/dist/lib/client.cjs +46 -0
  20. package/dist/lib/client.d.cts +2 -0
  21. package/dist/lib/client.d.ts +2 -0
  22. package/dist/lib/client.js +3 -3
  23. package/dist/lib/constants.cjs +11 -7
  24. package/dist/lib/constants.d.cts +2 -3
  25. package/dist/lib/constants.d.ts +2 -3
  26. package/dist/lib/constants.js +4 -6
  27. package/dist/lib/index.cjs +276 -163
  28. package/dist/lib/index.d.cts +6 -2
  29. package/dist/lib/index.d.ts +6 -2
  30. package/dist/lib/index.js +9 -6
  31. package/dist/react/index.cjs +524 -275
  32. package/dist/react/index.d.cts +20 -14
  33. package/dist/react/index.d.ts +20 -14
  34. package/dist/react/index.js +142 -98
  35. package/dist/react/utils.js +2 -2
  36. package/dist/tts/index.cjs +470 -0
  37. package/dist/tts/index.d.cts +17 -0
  38. package/dist/tts/index.d.ts +17 -0
  39. package/dist/tts/index.js +12 -0
  40. package/dist/tts/player.cjs +198 -0
  41. package/dist/tts/player.d.cts +43 -0
  42. package/dist/tts/player.d.ts +43 -0
  43. package/dist/tts/player.js +8 -0
  44. package/dist/tts/source.cjs +167 -0
  45. package/dist/tts/source.d.cts +53 -0
  46. package/dist/tts/source.d.ts +53 -0
  47. package/dist/tts/source.js +7 -0
  48. package/dist/{audio → tts}/utils.cjs +12 -53
  49. package/dist/tts/utils.d.cts +67 -0
  50. package/dist/tts/utils.d.ts +67 -0
  51. package/dist/{audio → tts}/utils.js +2 -7
  52. package/dist/{audio/index.cjs → tts/websocket.cjs} +213 -164
  53. package/dist/tts/websocket.d.cts +53 -0
  54. package/dist/tts/websocket.d.ts +53 -0
  55. package/dist/tts/websocket.js +11 -0
  56. package/dist/types/index.d.cts +50 -1
  57. package/dist/types/index.d.ts +50 -1
  58. package/dist/voices/index.cjs +155 -0
  59. package/dist/voices/index.d.cts +12 -0
  60. package/dist/voices/index.d.ts +12 -0
  61. package/dist/voices/index.js +9 -0
  62. package/package.json +2 -1
  63. package/src/index.ts +1 -0
  64. package/src/lib/client.ts +14 -1
  65. package/src/lib/constants.ts +13 -3
  66. package/src/lib/index.ts +6 -3
  67. package/src/react/index.ts +157 -103
  68. package/src/tts/index.ts +17 -0
  69. package/src/tts/player.ts +109 -0
  70. package/src/tts/source.ts +98 -0
  71. package/src/{audio → tts}/utils.ts +19 -97
  72. package/src/tts/websocket.ts +210 -0
  73. package/src/types/index.ts +63 -0
  74. package/src/voices/index.ts +47 -0
  75. package/dist/audio/index.d.cts +0 -5
  76. package/dist/audio/index.d.ts +0 -5
  77. package/dist/audio/index.js +0 -10
  78. package/dist/audio/utils.d.cts +0 -5
  79. package/dist/audio/utils.d.ts +0 -5
  80. package/dist/chunk-4MHF74A7.js +0 -272
  81. package/dist/chunk-5TSWLYOW.js +0 -113
  82. package/dist/chunk-MJIFZWHS.js +0 -18
  83. package/dist/chunk-OVI3W3GG.js +0 -12
  84. package/dist/chunk-S6A27RQL.js +0 -18
  85. package/dist/index-C2_3XFxn.d.cts +0 -163
  86. package/dist/index-DgwnZezj.d.ts +0 -163
  87. package/src/audio/index.ts +0 -297
@@ -1,100 +1,123 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
- import CartesiaAudio, { type Chunk, type StreamEventData } from "../audio";
3
- import { base64ToArray, bufferToWav } from "../audio/utils";
4
- import { SAMPLE_RATE } from "../lib/constants";
2
+ import { Cartesia } from "../lib";
3
+ import Player from "../tts/player";
4
+ import type Source from "../tts/source";
5
+ import type WebSocket from "../tts/websocket";
5
6
  import { pingServer } from "./utils";
6
7
 
7
- export type UseAudioOptions = {
8
+ export type UseTTSOptions = {
8
9
  apiKey: string | null;
9
10
  baseUrl?: string;
11
+ sampleRate: number;
10
12
  };
11
13
 
12
- interface UseAudioReturn {
13
- stream: (options: object) => void;
14
+ export type PlaybackStatus = "inactive" | "playing" | "paused" | "finished";
15
+ export type BufferStatus = "inactive" | "buffering" | "buffered";
16
+
17
+ export type Metrics = {
18
+ modelLatency: number | null;
19
+ };
20
+
21
+ export interface UseTTSReturn {
22
+ buffer: (options: object) => Promise<void>;
14
23
  play: (bufferDuration?: number) => Promise<void>;
15
- download: () => Blob | null;
16
- isPlaying: boolean;
24
+ pause: () => Promise<void>;
25
+ resume: () => Promise<void>;
26
+ toggle: () => Promise<void>;
27
+ source: Source | null;
28
+ playbackStatus: PlaybackStatus;
29
+ bufferStatus: BufferStatus;
30
+ isWaiting: boolean;
17
31
  isConnected: boolean;
18
- isStreamed: boolean;
19
- isBuffering: boolean;
20
- chunks: Chunk[];
21
- messages: StreamEventData["message"][];
32
+ metrics: Metrics;
22
33
  }
34
+
35
+ const PING_INTERVAL = 5000;
36
+ const DEFAULT_BUFFER_DURATION = 0.01;
37
+
38
+ type Message = {
39
+ step_time: number;
40
+ };
41
+
23
42
  /**
24
43
  * React hook to use the Cartesia audio API.
25
44
  */
26
- export function useAudio({ apiKey, baseUrl }: UseAudioOptions): UseAudioReturn {
45
+ export function useTTS({
46
+ apiKey,
47
+ baseUrl,
48
+ sampleRate,
49
+ }: UseTTSOptions): UseTTSReturn {
27
50
  if (typeof window === "undefined") {
28
51
  return {
29
- stream: () => {},
52
+ buffer: async () => {},
30
53
  play: async () => {},
31
- download: () => null,
54
+ pause: async () => {},
55
+ resume: async () => {},
56
+ toggle: async () => {},
57
+ playbackStatus: "inactive",
58
+ bufferStatus: "inactive",
59
+ isWaiting: false,
60
+ source: null,
32
61
  isConnected: false,
33
- isPlaying: false,
34
- isStreamed: false,
35
- isBuffering: false,
36
- chunks: [],
37
- messages: [],
62
+ metrics: {
63
+ modelLatency: null,
64
+ },
38
65
  };
39
66
  }
40
67
 
41
- const audio = useMemo(() => {
68
+ const websocket = useMemo(() => {
42
69
  if (!apiKey) {
43
70
  return null;
44
71
  }
45
- const audio = new CartesiaAudio({ apiKey, baseUrl });
46
- return audio;
47
- }, [apiKey, baseUrl]);
48
- const streamReturn = useRef<ReturnType<CartesiaAudio["stream"]> | null>(null);
49
- const [isStreamed, setIsStreamed] = useState(false);
50
- const [isPlaying, setIsPlaying] = useState(false);
51
- const [isBuffering, setIsBuffering] = useState(false);
72
+ const cartesia = new Cartesia({ apiKey, baseUrl });
73
+ baseUrl = baseUrl ?? cartesia.baseUrl;
74
+ return cartesia.tts.websocket({ sampleRate });
75
+ }, [apiKey, baseUrl, sampleRate]);
76
+ const websocketReturn = useRef<ReturnType<WebSocket["send"]> | null>(null);
77
+ const player = useRef<Player | null>(null);
78
+ const [playbackStatus, setPlaybackStatus] =
79
+ useState<PlaybackStatus>("inactive");
80
+ const [bufferStatus, setBufferStatus] = useState<BufferStatus>("inactive");
81
+ const [isWaiting, setIsWaiting] = useState(false);
52
82
  const [isConnected, setIsConnected] = useState(false);
53
- const [chunks, setChunks] = useState<Chunk[]>([]);
54
- const [messages, setMessages] = useState<StreamEventData["message"][]>([]);
83
+ const [bufferDuration, setBufferDuration] = useState<number | null>(null);
84
+ const [messages, setMessages] = useState<Message[]>([]);
55
85
 
56
- const latencyEndpoint = "https://api.cartesia.ai";
57
-
58
- const stream = useCallback(
86
+ const buffer = useCallback(
59
87
  async (options: object) => {
60
- setIsStreamed(false);
61
- streamReturn.current = audio?.stream(options) ?? null;
62
- if (!streamReturn.current) {
88
+ setMessages([]);
89
+ setBufferStatus("buffering");
90
+ websocketReturn.current = websocket?.send(options) ?? null;
91
+ if (!websocketReturn.current) {
63
92
  return;
64
93
  }
65
- setMessages([]);
66
- streamReturn.current.on(
67
- "chunk",
68
- ({ chunks }: StreamEventData["chunk"]) => {
69
- setChunks(chunks);
70
- },
71
- );
72
- streamReturn.current.on(
73
- "message",
74
- (message: StreamEventData["message"]) => {
75
- setMessages((messages) => [...messages, message]);
76
- },
77
- );
78
- const { chunks } = await streamReturn.current.once("streamed");
79
- setChunks(chunks);
80
- setIsStreamed(true);
94
+ websocketReturn.current.on("message", (message) => {
95
+ setMessages((messages) => [...messages, JSON.parse(message)]);
96
+ });
97
+ await websocketReturn.current.source.once("close");
98
+ setBufferStatus("buffered");
81
99
  },
82
- [audio],
100
+ [websocket],
83
101
  );
84
102
 
85
- const download = useCallback(() => {
86
- if (!isStreamed) {
87
- return null;
103
+ const metrics = useMemo(() => {
104
+ // Model Latency is the first step time
105
+ if (messages.length === 0) {
106
+ return {
107
+ modelLatency: null,
108
+ };
88
109
  }
89
- const audio = bufferToWav(SAMPLE_RATE, [base64ToArray(chunks)]);
90
- return new Blob([audio], { type: "audio/wav" });
91
- }, [isStreamed, chunks]);
110
+ const modelLatency = messages[0].step_time ?? null;
111
+ return {
112
+ modelLatency: Math.trunc(modelLatency),
113
+ };
114
+ }, [messages]);
92
115
 
93
116
  useEffect(() => {
94
117
  let cleanup: (() => void) | undefined = () => {};
95
118
  async function setupConnection() {
96
119
  try {
97
- const connection = await audio?.connect();
120
+ const connection = await websocket?.connect();
98
121
  if (!connection) {
99
122
  return;
100
123
  }
@@ -105,9 +128,25 @@ export function useAudio({ apiKey, baseUrl }: UseAudioOptions): UseAudioReturn {
105
128
  const unsubscribe = connection.on("close", () => {
106
129
  setIsConnected(false);
107
130
  });
131
+ const intervalId = setInterval(() => {
132
+ if (baseUrl) {
133
+ pingServer(new URL(baseUrl).origin).then((ping) => {
134
+ let bufferDuration: number;
135
+ if (ping < 300) {
136
+ bufferDuration = 0.01; // No buffering for very low latency
137
+ } else if (ping > 1500) {
138
+ bufferDuration = 6; // Max buffering for very high latency (6 seconds)
139
+ } else {
140
+ bufferDuration = (ping / 1000) * 4; // Adjust buffer duration based on ping
141
+ }
142
+ setBufferDuration(bufferDuration);
143
+ });
144
+ }
145
+ }, PING_INTERVAL);
108
146
  return () => {
109
147
  unsubscribe();
110
- audio?.disconnect();
148
+ clearInterval(intervalId);
149
+ websocket?.disconnect();
111
150
  };
112
151
  } catch (e) {
113
152
  console.error(e);
@@ -117,62 +156,77 @@ export function useAudio({ apiKey, baseUrl }: UseAudioOptions): UseAudioReturn {
117
156
  cleanup = cleanupConnection;
118
157
  });
119
158
  return () => cleanup?.();
120
- }, [audio]);
159
+ }, [websocket, baseUrl]);
121
160
 
122
161
  const play = useCallback(async () => {
123
- if (isPlaying || !streamReturn.current) {
162
+ if (playbackStatus === "playing" || !websocketReturn.current) {
124
163
  return;
125
164
  }
126
- setIsPlaying(true);
127
- const ping = await pingServer(latencyEndpoint);
128
- let bufferingTimeout: ReturnType<typeof setTimeout> | null;
129
-
130
- let bufferDuration: number;
131
- if (ping < 300) {
132
- bufferDuration = 0; // No buffering for very low latency
133
- } else if (ping > 1500) {
134
- bufferDuration = 6; // Max buffering for very high latency (6 seconds)
135
- } else {
136
- bufferDuration = (ping / 1000) * 4; // Adjust buffer duration based on ping
137
- }
165
+ setPlaybackStatus("playing");
138
166
 
139
- streamReturn.current.once("buffering").then(() => {
140
- bufferingTimeout = setTimeout(() => {
141
- setIsBuffering(true);
142
- }, 250); // Delay for 250ms before showing buffering indicator
143
- });
144
- streamReturn.current.once("buffered").then(() => {
145
- if (bufferingTimeout) {
146
- clearTimeout(bufferingTimeout); // Clear the timeout if buffering completes before 500ms
147
- }
148
- setIsBuffering(false);
149
- });
167
+ const unsubscribes = [];
168
+ unsubscribes.push(
169
+ websocketReturn.current.source.on("wait", () => {
170
+ setIsWaiting(true);
171
+ }),
172
+ );
173
+ unsubscribes.push(
174
+ websocketReturn.current.source.on("read", () => {
175
+ setIsWaiting(false);
176
+ }),
177
+ );
150
178
 
151
- // Wait for the playback to finish before setting isPlaying to false
152
- streamReturn.current.once("scheduled").then((data) => {
153
- setTimeout(() => {
154
- setIsPlaying(false);
155
- }, data.playbackEndsIn);
179
+ player.current = new Player({
180
+ bufferDuration: bufferDuration ?? DEFAULT_BUFFER_DURATION,
156
181
  });
182
+ // Wait for the playback to finish before setting isPlaying to false.
183
+ await player.current.play(websocketReturn.current.source);
184
+
185
+ for (const unsubscribe of unsubscribes) {
186
+ // Deregister the event listeners (.on()) that we registered above to avoid memory leaks.
187
+ unsubscribe();
188
+ }
157
189
 
158
- await streamReturn.current?.play({ bufferDuration });
159
- }, [isPlaying]);
190
+ setPlaybackStatus("finished");
191
+ }, [playbackStatus, bufferDuration]);
192
+
193
+ const pause = useCallback(async () => {
194
+ await player.current?.pause();
195
+ setPlaybackStatus("paused");
196
+ }, []);
197
+
198
+ const resume = useCallback(async () => {
199
+ await player.current?.resume();
200
+ setPlaybackStatus("playing");
201
+ }, []);
202
+
203
+ const toggle = useCallback(async () => {
204
+ await player.current?.toggle();
205
+ setPlaybackStatus((status) => {
206
+ if (status === "playing") {
207
+ return "paused";
208
+ }
209
+ if (status === "paused") {
210
+ return "playing";
211
+ }
212
+ return status;
213
+ });
214
+ }, []);
160
215
 
161
216
  // TODO:
162
- // - [] Pause and stop playback.
163
217
  // - [] Access the play and buffer cursors.
164
218
  // - [] Seek to a specific time.
165
- // These are probably best implemented by adding event listener
166
- // functionality to the base library.
167
219
  return {
168
- stream,
220
+ buffer,
169
221
  play,
170
- download,
171
- isPlaying,
222
+ pause,
223
+ source: websocketReturn.current?.source ?? null,
224
+ resume,
225
+ toggle,
226
+ playbackStatus,
227
+ bufferStatus,
228
+ isWaiting,
172
229
  isConnected,
173
- isStreamed,
174
- isBuffering,
175
- chunks,
176
- messages,
230
+ metrics,
177
231
  };
178
232
  }
@@ -0,0 +1,17 @@
1
+ import { Client } from "../lib/client";
2
+ import type { WebSocketOptions } from "../types";
3
+ import WebSocket from "./websocket";
4
+
5
+ export default class TTS extends Client {
6
+ /**
7
+ * Get a WebSocket client for streaming audio from the TTS API.
8
+ *
9
+ * @returns {WebSocket} A Cartesia WebSocket client.
10
+ */
11
+ websocket(options: WebSocketOptions): WebSocket {
12
+ return new WebSocket(options, {
13
+ apiKey: this.apiKey,
14
+ baseUrl: this.baseUrl,
15
+ });
16
+ }
17
+ }
@@ -0,0 +1,109 @@
1
+ import Emittery from "emittery";
2
+ import type Source from "./source";
3
+ import { playAudioBuffer } from "./utils";
4
+
5
+ type PlayEventData = {
6
+ finish: never;
7
+ };
8
+
9
+ export default class Player {
10
+ #context: AudioContext | null = null;
11
+ #startNextPlaybackAt = 0;
12
+ #bufferDuration: number;
13
+ #emitter = new Emittery<PlayEventData>();
14
+
15
+ /**
16
+ * Create a new Player.
17
+ *
18
+ * @param options - Options for the Player.
19
+ * @param options.bufferDuration - The duration of the audio buffer to play.
20
+ */
21
+ constructor({ bufferDuration }: { bufferDuration: number }) {
22
+ this.#bufferDuration = bufferDuration;
23
+ }
24
+
25
+ async #playBuffer(buf: Float32Array, sampleRate: number) {
26
+ if (!this.#context) {
27
+ throw new Error("AudioContext not initialized.");
28
+ }
29
+
30
+ const startAt = this.#startNextPlaybackAt;
31
+ const duration = buf.length / sampleRate;
32
+ this.#startNextPlaybackAt =
33
+ duration + Math.max(this.#context.currentTime, this.#startNextPlaybackAt);
34
+
35
+ await playAudioBuffer(buf, this.#context, startAt, sampleRate);
36
+ }
37
+
38
+ /**
39
+ * Play audio from a source.
40
+ *
41
+ * @param source The source to play audio from.
42
+ * @returns A promise that resolves when the audio has finished playing.
43
+ */
44
+ async play(source: Source) {
45
+ this.#startNextPlaybackAt = 0;
46
+ this.#context = new AudioContext({ sampleRate: source.sampleRate });
47
+ const buffer = new Float32Array(
48
+ source.durationToSampleCount(this.#bufferDuration),
49
+ );
50
+
51
+ const plays: Promise<void>[] = [];
52
+ while (true) {
53
+ const read = await source.read(buffer);
54
+ // If we've reached the end of the source, then read < buffer.length.
55
+ // In that case, we don't want to play the entire buffer, as that
56
+ // will cause repeated audio.
57
+ const playableAudio = buffer.slice(0, read);
58
+ plays.push(this.#playBuffer(playableAudio, source.sampleRate));
59
+
60
+ if (read < buffer.length) {
61
+ // No more audio to read.
62
+ await this.#emitter.emit("finish");
63
+ break;
64
+ }
65
+ }
66
+
67
+ await Promise.all(plays);
68
+ }
69
+
70
+ /**
71
+ * Pause the audio.
72
+ *
73
+ * @returns A promise that resolves when the audio has been paused.
74
+ */
75
+ async pause() {
76
+ if (!this.#context) {
77
+ throw new Error("AudioContext not initialized.");
78
+ }
79
+ await this.#context.suspend();
80
+ }
81
+
82
+ /**
83
+ * Resume the audio.
84
+ *
85
+ * @returns A promise that resolves when the audio has been resumed.
86
+ */
87
+ async resume() {
88
+ if (!this.#context) {
89
+ throw new Error("AudioContext not initialized.");
90
+ }
91
+ await this.#context.resume();
92
+ }
93
+
94
+ /**
95
+ * Toggle the audio.
96
+ *
97
+ * @returns A promise that resolves when the audio has been toggled.
98
+ */
99
+ async toggle() {
100
+ if (!this.#context) {
101
+ throw new Error("AudioContext not initialized.");
102
+ }
103
+ if (this.#context.state === "running") {
104
+ await this.pause();
105
+ } else {
106
+ await this.resume();
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,98 @@
1
+ import Emittery from "emittery";
2
+ import type { SourceEventData } from "../types";
3
+
4
+ export default class Source {
5
+ #emitter = new Emittery<SourceEventData>();
6
+ #buffer = new Float32Array();
7
+ #readIndex = 0;
8
+ #closed = false;
9
+ #sampleRate: number;
10
+
11
+ on = this.#emitter.on.bind(this.#emitter);
12
+ once = this.#emitter.once.bind(this.#emitter);
13
+ events = this.#emitter.events.bind(this.#emitter);
14
+ off = this.#emitter.off.bind(this.#emitter);
15
+
16
+ /**
17
+ * Create a new Source.
18
+ *
19
+ * @param options - Options for the Source.
20
+ * @param options.sampleRate - The sample rate of the audio.
21
+ */
22
+ constructor({ sampleRate }: { sampleRate: number }) {
23
+ this.#sampleRate = sampleRate;
24
+ }
25
+
26
+ get sampleRate() {
27
+ return this.#sampleRate;
28
+ }
29
+
30
+ /**
31
+ * Append audio to the buffer.
32
+ *
33
+ * @param src The audio to append.
34
+ */
35
+ async enqueue(src: Float32Array) {
36
+ // Append the audio to the buffer.
37
+ this.#buffer = new Float32Array([...this.#buffer, ...src]);
38
+ await this.#emitter.emit("enqueue");
39
+ }
40
+
41
+ /**
42
+ * Read audio from the buffer.
43
+ *
44
+ * @param dst The buffer to read the audio into.
45
+ * @returns The number of samples read. If the source is closed, this will be
46
+ * less than the length of the provided buffer.
47
+ */
48
+ async read(dst: Float32Array): Promise<number> {
49
+ // Read the buffer into the provided buffer.
50
+ const targetReadIndex = this.#readIndex + dst.length;
51
+
52
+ while (!this.#closed && targetReadIndex > this.#buffer.length) {
53
+ // Wait for more audio to be enqueued.
54
+ await this.#emitter.emit("wait");
55
+ await Promise.race([
56
+ this.#emitter.once("enqueue"),
57
+ this.#emitter.once("close"),
58
+ ]);
59
+ await this.#emitter.emit("read");
60
+ }
61
+
62
+ const read = Math.min(dst.length, this.#buffer.length - this.#readIndex);
63
+ dst.set(this.#buffer.slice(this.#readIndex, this.#readIndex + read));
64
+ this.#readIndex += read;
65
+ return read;
66
+ }
67
+
68
+ /**
69
+ * Get the number of samples in a given duration.
70
+ *
71
+ * @param durationSecs The duration in seconds.
72
+ * @returns The number of samples.
73
+ */
74
+ durationToSampleCount(durationSecs: number) {
75
+ return Math.trunc(durationSecs * this.#sampleRate);
76
+ }
77
+
78
+ get buffer() {
79
+ return this.#buffer;
80
+ }
81
+
82
+ get readIndex() {
83
+ return this.#readIndex;
84
+ }
85
+
86
+ /**
87
+ * Close the source. This signals that no more audio will be enqueued.
88
+ *
89
+ * This will emit a "close" event.
90
+ *
91
+ * @returns A promise that resolves when the source is closed.
92
+ */
93
+ async close() {
94
+ this.#closed = true;
95
+ await this.#emitter.emit("close");
96
+ this.#emitter.clearListeners();
97
+ }
98
+ }