Open History to see the last commit
1import {
2 AudioModule,
3 RecordingPresets,
4 requestRecordingPermissionsAsync,
5 setAudioModeAsync,
6 setIsAudioActiveAsync,
7 type RecorderState,
8 type RecordingStatus,
9} from "expo-audio";
10import { File } from "expo-file-system";
11import { activateKeepAwakeAsync, deactivateKeepAwake } from "expo-keep-awake";
12import {
13 createContext,
14 use,
15 useCallback,
16 useEffect,
17 useId,
18 useRef,
19 useState,
20 type ReactNode,
21} from "react";
22import { AppState, Platform } from "react-native";
23import { useSharedValue } from "react-native-reanimated";
24
25import { getLocalVoiceTranscriber } from "../../native/voiceTranscription";
26import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene";
27import {
28 VOICE_RECORDING_LIMIT_SECONDS,
29 voiceInputBlocksSubmission,
30 type VoiceInputState,
31} from "@t3tools/client-runtime/voice-input";
32import { createLazyVoiceRecorder, type LazyVoiceRecorder } from "./lazyVoiceRecorder";
33import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
34import { VoiceInputSession } from "./voiceInputSession";
35
36const INITIAL_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
37const VOICE_METERING_INTERVAL_MS = 80;
38// The native constructor takes platform-flattened options, as `useAudioRecorder`
39// builds them with expo-audio's internal `createRecordingOptions`.
40const { ios: IOS_RECORDING_OPTIONS, android: ANDROID_RECORDING_OPTIONS } =
41 RecordingPresets.HIGH_QUALITY;
42const VOICE_RECORDING_OPTIONS = {
43 extension: RecordingPresets.HIGH_QUALITY.extension,
44 sampleRate: RecordingPresets.HIGH_QUALITY.sampleRate,
45 numberOfChannels: RecordingPresets.HIGH_QUALITY.numberOfChannels,
46 bitRate: RecordingPresets.HIGH_QUALITY.bitRate,
47 isMeteringEnabled: true,
48 ...(Platform.OS === "ios" ? IOS_RECORDING_OPTIONS : ANDROID_RECORDING_OPTIONS),
49};
50
51async function releaseVoiceRecordingAudio(): Promise<void> {
52 try {
53 await setAudioModeAsync({ allowsRecording: false });
54 } finally {
55 // Expo does not deactivate AVAudioSession when recording stops or its
56 // category changes. Explicit deactivation resumes interrupted app audio.
57 await setIsAudioActiveAsync(false);
58 }
59}
60
61async function configureVoiceRecordingAudio(): Promise<void> {
62 try {
63 await setAudioModeAsync({
64 allowsRecording: true,
65 interruptionMode: "doNotMix",
66 playsInSilentMode: true,
67 shouldPlayInBackground: false,
68 });
69 await setIsAudioActiveAsync(true);
70 } catch (error) {
71 try {
72 await releaseVoiceRecordingAudio();
73 } catch {
74 // Keep the setup error. The controller has not started a recorder yet.
75 }
76 throw error;
77 }
78}
79
80const VoiceInputContext = createContext<ReturnType<typeof useVoiceInputRuntime> | null>(null);
81
82export function VoiceInputProvider({ children }: { readonly children: ReactNode }) {
83 const runtime = useVoiceInputRuntime();
84 return <VoiceInputContext value={runtime}>{children}</VoiceInputContext>;
85}
86
87export function useGlobalVoiceInput() {
88 const context = use(VoiceInputContext);
89 if (!context) throw new Error("Voice input provider is missing.");
90 return context;
91}
92
93function useVoiceInputRuntime() {
94 const [{ state, ownerKey, label }, setState] = useState({
95 state: INITIAL_STATE,
96 ownerKey: null as string | null,
97 label: null as string | null,
98 });
99 const [focusedOwners, setFocusedOwners] = useState<ReadonlySet<string>>(new Set());
100 const setOwnerFocused = useCallback((key: string, focused: boolean) => {
101 setFocusedOwners((current) => {
102 const next = new Set(current);
103 if (focused) next.add(key);
104 else next.delete(key);
105 return next;
106 });
107 }, []);
108 const [elapsedSeconds, setElapsedSeconds] = useState(0);
109 const keepAwakeId = useId();
110 const keepAwakeSessionRef = useRef(0);
111 const elapsedSecondsRef = useRef(0);
112 const audioLevelsRef = useRef(Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0));
113 const audioLevels = useSharedValue(audioLevelsRef.current);
114 const sessionRef = useRef<VoiceInputSession | null>(null);
115 const recorderRef = useRef<LazyVoiceRecorder<RecorderState> | null>(null);
116
117 if (!sessionRef.current || !recorderRef.current) {
118 // The native recorder is created when dictation starts, not on app launch.
119 const recorder = createLazyVoiceRecorder({
120 create: () => new AudioModule.AudioRecorder(VOICE_RECORDING_OPTIONS),
121 onStatus: (status: RecordingStatus) => {
122 sessionRef.current?.controller.handleRecorderStatus({
123 isFinished: status.isFinished,
124 hasError: status.hasError || status.mediaServicesDidReset === true,
125 error: status.error,
126 url: status.url,
127 });
128 },
129 });
130 recorderRef.current = recorder;
131 sessionRef.current = new VoiceInputSession({
132 recorder,
133 getTranscriber: getLocalVoiceTranscriber,
134 requestPermission: async () => {
135 const permission = await requestRecordingPermissionsAsync();
136 return { granted: permission.granted, canAskAgain: permission.canAskAgain };
137 },
138 configureRecording: configureVoiceRecordingAudio,
139 releaseRecording: releaseVoiceRecordingAudio,
140 deleteRecording: (uri) => new File(uri).delete(),
141 onStateChange: (nextState) =>
142 setState({
143 state: nextState,
144 ownerKey: sessionRef.current?.ownerKey ?? null,
145 label: sessionRef.current?.label ?? null,
146 }),
147 });
148 }
149
150 const session = sessionRef.current;
151 const controller = session.controller;
152 const recorder = recorderRef.current;
153
154 useEffect(() => {
155 const subscription = AppState.addEventListener("change", (nextState) => {
156 // iOS reports `inactive` while its permission dialog is open. Only the
157 // real background state cancels preparation; recorder status handles
158 // calls and route interruptions during capture.
159 if (nextState === "background") controller.appMovedToBackground();
160 });
161 return () => subscription.remove();
162 }, [controller]);
163
164 useEffect(
165 () => () => {
166 // Dispose first so an active recording is stopped before the recorder is released.
167 controller.dispose();
168 recorder.release();
169 },
170 [controller, recorder],
171 );
172
173 useEffect(() => {
174 if (state.phase !== "recording") return;
175
176 const tag = `voice-input:${keepAwakeId}:${++keepAwakeSessionRef.current}`;
177 const activation = activateKeepAwakeAsync(tag);
178 void activation.catch(() => {});
179 return () => {
180 // Release after activation settles, even if the recording ends immediately.
181 void activation.then(() => deactivateKeepAwake(tag)).catch(() => {});
182 };
183 }, [keepAwakeId, state.phase]);
184
185 useEffect(() => {
186 if (state.phase !== "preparing" && state.phase !== "recording") return;
187
188 if (audioLevelsRef.current.some((level) => level !== 0)) {
189 audioLevelsRef.current = Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0);
190 audioLevels.value = audioLevelsRef.current;
191 }
192 if (elapsedSecondsRef.current !== 0) {
193 elapsedSecondsRef.current = 0;
194 setElapsedSeconds(0);
195 }
196 if (state.phase !== "recording") return;
197
198 const sampleRecording = () => {
199 if (controller.currentState.phase !== "recording") return;
200 const status = recorder.getStatus();
201 if (!status?.isRecording) return;
202
203 const level = normalizeVoiceInputDecibels(status.metering);
204 const history = audioLevelsRef.current;
205 if (level !== 0 || history.some((sample) => sample !== 0)) {
206 const nextLevels = [...history.slice(1), level];
207 audioLevelsRef.current = nextLevels;
208 audioLevels.value = nextLevels;
209 }
210
211 const nextElapsedSeconds = Math.min(
212 VOICE_RECORDING_LIMIT_SECONDS,
213 Math.max(0, Math.floor(status.durationMillis / 1_000)),
214 );
215 if (nextElapsedSeconds !== elapsedSecondsRef.current) {
216 elapsedSecondsRef.current = nextElapsedSeconds;
217 setElapsedSeconds(nextElapsedSeconds);
218 }
219 };
220
221 sampleRecording();
222 const intervalId = setInterval(sampleRecording, VOICE_METERING_INTERVAL_MS);
223 return () => clearInterval(intervalId);
224 }, [audioLevels, controller, recorder, state.phase]);
225
226 const stop = useCallback(() => controller.stop(), [controller]);
227 const cancel = useCallback(() => controller.cancel(), [controller]);
228
229 return {
230 // Store screenshots show the dictation button even on simulators, whose
231 // on-device transcription is unavailable.
232 isAvailable: getLocalVoiceTranscriber() !== null || getNativeShowcaseScene() !== null,
233 state,
234 audioLevels,
235 elapsedSeconds,
236 isBusy: voiceInputBlocksSubmission(state),
237 ownerKey,
238 label,
239 focusedOwners,
240 setOwnerFocused,
241 session,
242 stop,
243 cancel,
244 };
245}