Open History to see the last commit
1import type {
2 PreparedVoiceTranscription,
3 VoiceRecorder,
4 VoiceStreamingSession,
5 VoiceInputErrorCode,
6 VoiceTranscriptionOptions,
7} from "@t3tools/client-runtime/voice-input";
8import { requestMicrophone } from "./requestMicrophone";
9import workletUrl from "./pcmWorklet.ts?worker&url";
10import { msg } from "gt-react";
11import { m } from "../i18n/messages";
12
13type PreparedBrowserTranscription = PreparedVoiceTranscription & {
14 readonly streaming?: VoiceStreamingSession & { readonly feed: (pcm: Float32Array) => void };
15};
16
17export function createBrowserPcmCapture(
18 input: {
19 readonly getMicrophoneId: () => string | Promise<string>;
20 readonly onLevel: (level: number) => void;
21 readonly onDurationLimit: () => void;
22 readonly onError: (message: string, code?: VoiceInputErrorCode) => void;
23 },
24 prepare: (options: VoiceTranscriptionOptions) => Promise<PreparedBrowserTranscription>,
25) {
26 let stream: MediaStream | undefined;
27 let recordingUri: string | null = null;
28 let chunks: Float32Array<ArrayBuffer>[] = [];
29 let audioContext: AudioContext | undefined;
30 let worklet: AudioWorkletNode | undefined;
31 let durationTimer: ReturnType<typeof setTimeout> | undefined;
32 let signal: AbortSignal | undefined;
33 let feed: ((pcm: Float32Array) => void) | undefined;
34 let stopped:
35 | { readonly resolve: () => void; readonly reject: (error: Error) => void }
36 | undefined;
37
38 const cleanupCapture = () => {
39 if (durationTimer) clearTimeout(durationTimer);
40 durationTimer = undefined;
41 worklet?.disconnect();
42 worklet?.port.close();
43 worklet = undefined;
44 stream?.getTracks().forEach((track) => track.stop());
45 stream = undefined;
46 void audioContext?.close();
47 audioContext = undefined;
48 stopped?.resolve();
49 stopped = undefined;
50 chunks = [];
51 feed = undefined;
52 input.onLevel(0);
53 };
54
55 const recorder: VoiceRecorder = {
56 get uri() {
57 return recordingUri;
58 },
59 prepareToRecordAsync: async () => {
60 const captureSignal = signal;
61 if (!captureSignal) throw new Error(m(msg("Voice transcription is not prepared.")));
62 captureSignal.throwIfAborted();
63 if (recordingUri) URL.revokeObjectURL(recordingUri);
64 recordingUri = null;
65 chunks = [];
66 const microphoneId = await input.getMicrophoneId();
67 captureSignal.throwIfAborted();
68 const captured = await new Promise<MediaStream>((resolve, reject) => {
69 const onAbort = () => reject(captureSignal.reason);
70 const permission = requestMicrophone(microphoneId, captureSignal);
71 captureSignal.addEventListener("abort", onAbort, { once: true });
72 void permission.then(
73 (media) => {
74 captureSignal.removeEventListener("abort", onAbort);
75 if (captureSignal.aborted) media.getTracks().forEach((track) => track.stop());
76 else resolve(media);
77 },
78 (error: unknown) => {
79 captureSignal.removeEventListener("abort", onAbort);
80 reject(error);
81 },
82 );
83 });
84 if (captureSignal.aborted) {
85 captured.getTracks().forEach((track) => track.stop());
86 captureSignal.throwIfAborted();
87 }
88 stream = captured;
89 try {
90 const context = new AudioContext();
91 audioContext = context;
92 await context.audioWorklet.addModule(workletUrl);
93 captureSignal.throwIfAborted();
94 const node = new AudioWorkletNode(context, "t3-pcm-capture", { channelCount: 1 });
95 worklet = node;
96 node.port.onmessage = ({
97 data,
98 }: MessageEvent<Float32Array<ArrayBuffer> | number | "stopped" | "limit">) => {
99 if (captureSignal.aborted) return;
100 if (data === "stopped") {
101 stopped?.resolve();
102 return;
103 }
104 if (data === "limit") {
105 input.onDurationLimit();
106 return;
107 }
108 if (typeof data === "number") {
109 input.onLevel(data);
110 return;
111 }
112 if (feed) feed(data);
113 else chunks.push(data);
114 };
115 node.onprocessorerror = () => {
116 stopped?.reject(new Error(m(msg("Microphone processing failed."))));
117 input.onError(m(msg("Microphone processing failed.")), "microphone-failed");
118 };
119 for (const track of captured.getTracks())
120 track.addEventListener(
121 "ended",
122 () => input.onError(m(msg("The microphone disconnected.")), "microphone-disconnected"),
123 {
124 once: true,
125 },
126 );
127 context.createMediaStreamSource(captured).connect(node);
128 // The processor emits silence, keeping the graph active without microphone playback.
129 node.connect(context.destination);
130 await context.resume();
131 captureSignal.throwIfAborted();
132 } catch (error) {
133 cleanupCapture();
134 throw error;
135 }
136 },
137 record: ({ forDuration }) => {
138 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- AudioWorklet MessagePorts do not accept a target origin
139 worklet?.port.postMessage("start");
140 durationTimer = setTimeout(input.onDurationLimit, forDuration * 1_000);
141 },
142 stop: async () => {
143 if (!worklet) return;
144 if (signal?.aborted) {
145 cleanupCapture();
146 return;
147 }
148 const pending = new Promise<void>((resolve, reject) => {
149 stopped = { resolve, reject };
150 });
151 const timeout = setTimeout(
152 () => stopped?.reject(new Error(m(msg("Microphone capture did not stop.")))),
153 5_000,
154 );
155 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- AudioWorklet MessagePorts do not accept a target origin
156 worklet.port.postMessage("stop");
157 try {
158 await pending;
159 if (!feed && chunks.length) {
160 const blob = new Blob(chunks, { type: "application/octet-stream" });
161 recordingUri = URL.createObjectURL(blob);
162 }
163 } finally {
164 clearTimeout(timeout);
165 cleanupCapture();
166 }
167 },
168 };
169
170 return {
171 recorder,
172 cancelRecording: cleanupCapture,
173 deleteRecording: (uri: string) => {
174 URL.revokeObjectURL(uri);
175 if (recordingUri === uri) recordingUri = null;
176 },
177 transcriber: {
178 prepare: async (options: VoiceTranscriptionOptions) => {
179 const prepared = await prepare(options);
180 options.signal.throwIfAborted();
181 signal = options.signal;
182 feed = prepared.streaming?.feed;
183 return prepared;
184 },
185 },
186 };
187}