Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

browserPcmCapture.ts

180 lines6.1 KB

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