Files
DeepTutor/web/hooks/useVoiceRecorder.ts
ZQR1101 ac25a5c868 fix(voice): strip MediaRecorder codec params from STT uploads (#948)
* fix(voice): strip MediaRecorder codec params from STT uploads

Chrome sends audio/webm;codecs=opus; OpenAI-compatible transcription APIs reject that as an unknown format.

Fixes #945

* refactor(voice): normalize the STT MIME once, at the wire boundary

The codec-parameter strip was applied at four layers: the recorder hook, the
route, the `transcribe_audio` facade, and `_post_multipart`. Only the last of
those decides what actually goes on the wire, and `openai_compat` is the sole
registered STT adapter, so the two middle copies were pure duplication —
and they made the route's contract ambiguous about who owns the value.

Keep the client-side strip (it sets the Blob type, which is what the browser
puts in the multipart part) and the adapter strip; drop the route and facade
copies along with the now-unused facade re-export. The adapter-level test
already pins the wire contract; the route test now asserts what the route
actually promises — verbatim forwarding.

---------

Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
Co-authored-by: Frank <bingxizhao@novix.science>
2026-08-24 16:51:49 +08:00

120 lines
3.9 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { apiFetch, apiUrl } from "@/lib/api";
import { stripAudioMimeParameters } from "@/lib/voice-mime";
export type RecorderState = "idle" | "recording" | "transcribing";
/**
* Microphone capture → backend transcription. Records via MediaRecorder, posts
* the clip to ``/api/v1/voice/stt`` (which uses the admin-configured STT
* provider), and hands the transcript back through ``onTranscript``.
*/
export function useVoiceRecorder(onTranscript: (text: string) => void) {
const [state, setState] = useState<RecorderState>("idle");
const [error, setError] = useState<string | null>(null);
const recorderRef = useRef<MediaRecorder | null>(null);
const chunksRef = useRef<Blob[]>([]);
const streamRef = useRef<MediaStream | null>(null);
const onTranscriptRef = useRef(onTranscript);
onTranscriptRef.current = onTranscript;
const releaseStream = useCallback(() => {
streamRef.current?.getTracks().forEach((track) => track.stop());
streamRef.current = null;
}, []);
const start = useCallback(async () => {
if (state !== "idle") return;
setError(null);
if (
typeof navigator === "undefined" ||
!navigator.mediaDevices?.getUserMedia ||
typeof MediaRecorder === "undefined"
) {
setError("Recording is not supported in this browser.");
return;
}
let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch {
setError("Microphone permission denied.");
return;
}
streamRef.current = stream;
const recorder = new MediaRecorder(stream);
chunksRef.current = [];
recorder.ondataavailable = (event) => {
if (event.data && event.data.size > 0) chunksRef.current.push(event.data);
};
recorder.onstop = async () => {
const mimeType = stripAudioMimeParameters(recorder.mimeType);
releaseStream();
const blob = new Blob(chunksRef.current, { type: mimeType });
chunksRef.current = [];
if (!blob.size) {
setState("idle");
return;
}
setState("transcribing");
try {
const ext = mimeType.includes("ogg")
? "ogg"
: mimeType.includes("mp4")
? "mp4"
: "webm";
const form = new FormData();
form.append("file", blob, `recording.${ext}`);
const resp = await apiFetch(apiUrl("/api/v1/voice/stt"), {
method: "POST",
body: form,
});
if (!resp.ok) {
const detail = (await resp.json().catch(() => null)) as {
detail?: string;
} | null;
throw new Error(
detail?.detail || `Transcription failed (HTTP ${resp.status}).`,
);
}
const data = (await resp.json()) as { text?: string };
const text = (data.text || "").trim();
if (text) onTranscriptRef.current(text);
} catch (err) {
setError(err instanceof Error ? err.message : "Transcription failed.");
} finally {
setState("idle");
}
};
recorder.start();
recorderRef.current = recorder;
setState("recording");
}, [releaseStream, state]);
const stop = useCallback(() => {
const recorder = recorderRef.current;
if (recorder && recorder.state !== "inactive") {
recorder.stop(); // fires onstop → transcribe
}
}, []);
const toggle = useCallback(() => {
if (state === "recording") stop();
else if (state === "idle") void start();
}, [start, state, stop]);
// Stop the mic if the component unmounts mid-recording.
useEffect(() => {
return () => {
const recorder = recorderRef.current;
if (recorder && recorder.state !== "inactive") recorder.stop();
streamRef.current?.getTracks().forEach((track) => track.stop());
};
}, []);
return { state, error, toggle, start, stop };
}