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

environmentTranscriber.ts

65 lines2.2 KB

1import { msg } from "gt-react-native";
2​
3import { m } from "../../i18n/messages";
4import {
5 VoiceTranscriptionError,
6 VOICE_RECORDING_LIMIT_SECONDS,
7 throwIfVoiceTranscriptionAborted,
8 type VoiceTranscriber,
9} from "@t3tools/client-runtime/voice-input";
10​
11const pcmBytesPerSecond = 16_000 * 2;
12const maxPcmBytes = pcmBytesPerSecond * VOICE_RECORDING_LIMIT_SECONDS;
13​
14export function createEnvironmentTranscriber(input: {
15 readonly canSend: () => boolean;
16 readonly prepare: (signal: AbortSignal) => Promise<string>;
17 readonly decode: (uri: string) => Promise<Uint8Array>;
18 readonly upload: (pcm: Uint8Array, signal: AbortSignal) => Promise<string>;
19}): VoiceTranscriber {
20 function check(signal: AbortSignal) {
21 throwIfVoiceTranscriptionAborted(signal);
22 if (!input.canSend()) {
23 throw new VoiceTranscriptionError({
24 code: "cancelled",
25 message: m(msg("Your transcription choice changed.")),
26 });
27 }
28 }
29 return {
30 async prepare({ signal }) {
31 check(signal);
32 const locale = await input.prepare(signal);
33 check(signal);
34 return {
35 locale,
36 async transcribe(uri, { signal }) {
37 check(signal);
38 const decoded = await input.decode(uri);
39 check(signal);
40 if (
41 !decoded.length ||
42 decoded.length % 2 ||
43 decoded.length > maxPcmBytes + pcmBytesPerSecond
44 ) {
45 throw new VoiceTranscriptionError({
46 code: "transcription-failed",
47 message: m(msg("This recording couldn’t be read. Try recording again.")),
48 });
49 }
50 // A timed native stop can include a final encoder packet beyond the recording limit.
51 const bytes = decoded.subarray(0, maxPcmBytes);
52 const samples =
53 bytes.byteOffset % 2 === 0
54 ? new Int16Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 2)
55 : new Int16Array(Uint8Array.from(bytes).buffer);
56 const pcm = new Float32Array(samples.length);
57 for (let i = 0; i < samples.length; i++) pcm[i] = samples[i]! / 32768;
58 const text = await input.upload(new Uint8Array(pcm.buffer), signal);
59 check(signal);
60 return text;
61 },
62 };
63 },
64 };