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

MicrophoneTest.tsx

350 lines11.6 KB

1import { MICROPHONE_PERMISSION_ERROR } from "@t3tools/client-runtime/voice-input";
2import { CheckIcon, MicIcon, PauseIcon, PlayIcon, RotateCcwIcon, XIcon } from "lucide-react";
3import { useEffect, useRef, useState } from "react";
4​
5import { useStableCallback } from "~/hooks/useStableCallback";
6import workletUrl from "../../speech/pcmWorklet.ts?worker&url";
7import { VoiceInputErrorPill } from "../chat/VoiceInputErrorPill";
8import { VoiceInputPill, VoiceWaveform } from "../chat/VoiceInputPill";
9import { Button } from "../ui/button";
10​
11const LOOPBACK_SECONDS = 10;
12const formatTime = (seconds: number) =>
13 `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`;
14​
15type Capture = {
16 stream?: MediaStream;
17 recorder?: MediaRecorder;
18 context?: AudioContext;
19 worklet?: AudioWorkletNode;
20 timer?: ReturnType<typeof setTimeout>;
21 elapsedTimer?: ReturnType<typeof setInterval>;
22 startedAt?: number;
23};
24​
25/**
26 * Records a few seconds and plays them back in the browser. The audio never leaves this
27 * device: no environment, transcriber, or provider is involved, so a silent result points
28 * at the microphone rather than at transcription.
29 */
30export function MicrophoneTest({ microphoneId }: { microphoneId: string }) {
31 const [phase, setPhase] = useState<"idle" | "starting" | "recording" | "ready">("idle");
32 const [recording, setRecording] = useState<{ url: string; duration: number } | null>(null);
33 const [error, setError] = useState<string | null>(null);
34 const [level, setLevel] = useState(0);
35 const [elapsed, setElapsed] = useState(0);
36 const capture = useRef<Capture | null>(null);
37 const recordingUrl = useRef<string | null>(null);
38​
39 const releaseCapture = useStableCallback(() => {
40 const current = capture.current;
41 if (!current) return;
42 capture.current = null;
43 clearTimeout(current.timer);
44 clearInterval(current.elapsedTimer);
45 current.worklet?.disconnect();
46 current.worklet?.port.close();
47 if (current.recorder && current.recorder.state !== "inactive") current.recorder.stop();
48 current.stream?.getTracks().forEach((track) => track.stop());
49 void current.context?.close().catch(() => undefined);
50 });
51 const discard = () => {
52 if (recordingUrl.current) URL.revokeObjectURL(recordingUrl.current);
53 recordingUrl.current = null;
54 setRecording(null);
55 setPhase("idle");
56 };
57 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases the microphone and the recording's object URL on unmount
58 useEffect(
59 () => () => {
60 releaseCapture();
61 if (recordingUrl.current) URL.revokeObjectURL(recordingUrl.current);
62 },
63 [releaseCapture],
64 );
65​
66 const start = async () => {
67 releaseCapture();
68 discard();
69 setError(null);
70 setLevel(0);
71 setElapsed(0);
72 setPhase("starting");
73 if (
74 !navigator.mediaDevices?.getUserMedia ||
75 typeof MediaRecorder === "undefined" ||
76 typeof AudioWorkletNode === "undefined"
77 ) {
78 setError("Microphone testing is unavailable in this browser. Use HTTPS or the desktop app.");
79 setPhase("idle");
80 return;
81 }
82 const current: Capture = {};
83 capture.current = current;
84 try {
85 const stream = await navigator.mediaDevices.getUserMedia({
86 audio: microphoneId ? { deviceId: { exact: microphoneId } } : true,
87 });
88 if (capture.current !== current) {
89 stream.getTracks().forEach((track) => track.stop());
90 return;
91 }
92 current.stream = stream;
93 const recorder = new MediaRecorder(stream);
94 current.recorder = recorder;
95 const chunks: Blob[] = [];
96 recorder.addEventListener("dataavailable", ({ data }) => {
97 if (capture.current === current && data.size) chunks.push(data);
98 });
99 recorder.addEventListener("stop", () => {
100 if (capture.current !== current) return;
101 const blob = new Blob(chunks, { type: recorder.mimeType });
102 const duration =
103 current.startedAt === undefined ? 0 : (performance.now() - current.startedAt) / 1_000;
104 releaseCapture();
105 setLevel(0);
106 if (!blob.size) {
107 setError("No audio was recorded. Try again.");
108 setPhase("idle");
109 return;
110 }
111 recordingUrl.current = URL.createObjectURL(blob);
112 setRecording({ url: recordingUrl.current, duration });
113 setPhase("ready");
114 });
115 const onRecordingError = () => {
116 if (capture.current !== current) return;
117 releaseCapture();
118 setLevel(0);
119 setError("Could not record microphone audio. Try again.");
120 setPhase("idle");
121 };
122 recorder.addEventListener("error", onRecordingError);
123 for (const track of stream.getAudioTracks()) {
124 track.addEventListener(
125 "ended",
126 () => {
127 if (capture.current !== current) return;
128 setError("The microphone disconnected.");
129 if (recorder.state !== "inactive") recorder.stop();
130 },
131 { once: true },
132 );
133 }
134 const context = new AudioContext();
135 current.context = context;
136 await context.audioWorklet.addModule(workletUrl);
137 if (capture.current !== current) return;
138 const worklet = new AudioWorkletNode(context, "t3-pcm-capture", {
139 channelCount: 1,
140 processorOptions: { meterOnly: true },
141 });
142 current.worklet = worklet;
143 worklet.port.onmessage = ({ data }: MessageEvent<number | "stopped">) => {
144 if (capture.current === current && typeof data === "number") setLevel(data);
145 };
146 worklet.onprocessorerror = onRecordingError;
147 context.createMediaStreamSource(stream).connect(worklet);
148 worklet.connect(context.destination);
149 await context.resume();
150 if (capture.current !== current) return;
151 const startedAt = performance.now();
152 current.startedAt = startedAt;
153 current.elapsedTimer = setInterval(() => {
154 setElapsed(Math.min(LOOPBACK_SECONDS, Math.floor((performance.now() - startedAt) / 1_000)));
155 }, 100);
156 recorder.start();
157 worklet.port.postMessage("start", []);
158 setPhase("recording");
159 current.timer = setTimeout(() => {
160 if (recorder.state !== "inactive") recorder.stop();
161 }, LOOPBACK_SECONDS * 1_000);
162 } catch (cause) {
163 if (capture.current !== current) return;
164 releaseCapture();
165 setPhase("idle");
166 setError(
167 typeof cause === "object" &&
168 cause !== null &&
169 "name" in cause &&
170 cause.name === "NotAllowedError"
171 ? MICROPHONE_PERMISSION_ERROR
172 : cause instanceof Error
173 ? cause.message
174 : "Could not access the microphone.",
175 );
176 }
177 };
178 const cancel = () => {
179 releaseCapture();
180 discard();
181 setError(null);
182 };
183​
184 if (error) {
185 return (
186 <VoiceInputErrorPill
187 error={error}
188 errorAction="retry"
189 onRetry={() => void start()}
190 onDismiss={cancel}
191 />
192 );
193 }
194 if (phase === "idle") {
195 return (
196 <Button size="sm" variant="outline" onClick={() => void start()}>
197 <MicIcon />
198 Test microphone
199 </Button>
200 );
201 }
202 if (phase === "ready" && recording) {
203 return (
204 <MicrophonePlayback
205 key={recording.url}
206 src={recording.url}
207 duration={recording.duration}
208 onRetry={() => void start()}
209 onDone={cancel}
210 />
211 );
212 }
213 return (
214 <VoiceInputPill>
215 <Button
216 size="icon-sm-pill"
217 variant="ghost"
218 aria-label="Cancel microphone test"
219 onClick={cancel}
220 >
221 <XIcon />
222 </Button>
223 {phase === "recording" ? (
224 <>
225 <VoiceWaveform level={level} />
226 <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-primary" />
227 <span
228 className="shrink-0 text-xs tabular-nums text-muted-foreground"
229 aria-label="Recording time"
230 >
231 {formatTime(elapsed)} / {formatTime(LOOPBACK_SECONDS)}
232 </span>
233 <meter
234 aria-label="Microphone input level"
235 min={0}
236 max={1}
237 value={level}
238 className="sr-only"
239 />
240 </>
241 ) : (
242 <span role="status" className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
243 Opening microphone…
244 </span>
245 )}
246 <Button
247 size="icon-sm-pill"
248 aria-label="Stop recording"
249 disabled={phase !== "recording"}
250 onClick={() => {
251 const recorder = capture.current?.recorder;
252 if (recorder && recorder.state !== "inactive") recorder.stop();
253 }}
254 >
255 <CheckIcon />
256 </Button>
257 </VoiceInputPill>
258 );
260​
261function MicrophonePlayback({
262 src,
263 duration,
264 onRetry,
265 onDone,
266}: {
267 src: string;
268 duration: number;
269 onRetry(): void;
270 onDone(): void;
271}) {
272 const audio = useRef<HTMLAudioElement>(null);
273 const [playing, setPlaying] = useState(false);
274 const [position, setPosition] = useState(0);
275 const [failed, setFailed] = useState(false);
276 const progress = duration > 0 ? Math.min(position / duration, 1) * 100 : 0;
277​
278 const togglePlayback = async () => {
279 const player = audio.current;
280 if (!player) return;
281 if (!player.paused) {
282 player.pause();
283 return;
284 }
285 setFailed(false);
286 if (player.ended) player.currentTime = 0;
287 try {
288 await player.play();
289 } catch {
290 setFailed(true);
291 }
292 };
293​
294 return (
295 <div className="flex flex-col gap-1">
296 <audio
297 ref={audio}
298 src={src}
299 preload="metadata"
300 onPlay={() => setPlaying(true)}
301 onPause={() => setPlaying(false)}
302 onEnded={() => setPlaying(false)}
303 onTimeUpdate={() => setPosition(audio.current?.currentTime ?? 0)}
304 onError={() => setFailed(true)}
305 />
306 <VoiceInputPill>
307 <Button
308 size="icon-sm-pill"
309 variant="ghost"
310 aria-label={playing ? "Pause recording" : "Play recording"}
311 onClick={() => void togglePlayback()}
312 >
313 {playing ? <PauseIcon /> : <PlayIcon />}
314 </Button>
315 <input
316 type="range"
317 aria-label="Recording playback position"
318 min={0}
319 max={duration}
320 step={0.01}
321 value={Math.min(position, duration)}
322 style={{
323 background: `linear-gradient(to right, var(--primary) ${progress}%, var(--muted) ${progress}%)`,
324 }}
325 disabled={duration <= 0}
326 onChange={(event) => {
327 const next = Number(event.target.value);
328 if (audio.current) audio.current.currentTime = next;
329 setPosition(next);
330 }}
331 className="h-1 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring [&::-webkit-slider-thumb]:size-2.5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:size-2.5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-primary"
332 />
333 <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
334 {formatTime(position)}
335 </span>
336 <Button size="icon-sm-pill" variant="ghost" aria-label="Record again" onClick={onRetry}>
337 <RotateCcwIcon />
338 </Button>
339 <Button size="icon-sm-pill" aria-label="Done" onClick={onDone}>
340 <CheckIcon />
341 </Button>
342 </VoiceInputPill>
343 {failed ? (
344 <p role="alert" className="text-xs text-destructive">
345 Could not play this recording. Try recording again.
346 </p>
347 ) : null}
348 </div>
349 );