fix(audio-message): ios + up to expo-audio
This commit is contained in:
parent
bc5129f7bf
commit
4d71c229d6
4 changed files with 389 additions and 175 deletions
|
|
@ -120,7 +120,6 @@
|
||||||
"eventemitter3": "^5.0.1",
|
"eventemitter3": "^5.0.1",
|
||||||
"expo": "~53.0.23",
|
"expo": "~53.0.23",
|
||||||
"expo-audio": "~0.4.9",
|
"expo-audio": "~0.4.9",
|
||||||
"expo-av": "~15.1.7",
|
|
||||||
"expo-build-properties": "~0.14.8",
|
"expo-build-properties": "~0.14.8",
|
||||||
"expo-constants": "~17.1.7",
|
"expo-constants": "~17.1.7",
|
||||||
"expo-contacts": "~14.2.5",
|
"expo-contacts": "~14.2.5",
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,9 @@
|
||||||
import React, { useState, useCallback, useEffect, useRef } from "react";
|
import React, { useState, useCallback, useEffect, useRef } from "react";
|
||||||
import { View, Text, TouchableOpacity, Platform, Alert } from "react-native";
|
import { View, Text, TouchableOpacity, Platform, Alert } from "react-native";
|
||||||
|
import * as Sentry from "@sentry/react-native";
|
||||||
import { MaterialCommunityIcons } from "@expo/vector-icons";
|
import { MaterialCommunityIcons } from "@expo/vector-icons";
|
||||||
import {
|
import { createAudioPlayer, setAudioModeAsync } from "expo-audio";
|
||||||
useAudioRecorder,
|
import * as Device from "expo-device";
|
||||||
createAudioPlayer,
|
|
||||||
setAudioModeAsync,
|
|
||||||
requestRecordingPermissionsAsync,
|
|
||||||
RecordingPresets,
|
|
||||||
IOSOutputFormat,
|
|
||||||
AudioQuality,
|
|
||||||
} from "expo-audio";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
check,
|
check,
|
||||||
|
|
@ -27,6 +21,7 @@ import network from "~/network";
|
||||||
|
|
||||||
import TextArea from "./TextArea";
|
import TextArea from "./TextArea";
|
||||||
import useInsertMessage from "~/hooks/useInsertMessage";
|
import useInsertMessage from "~/hooks/useInsertMessage";
|
||||||
|
import useVoiceRecorder from "~/hooks/useVoiceRecorder";
|
||||||
import { announceForA11y } from "~/lib/a11y";
|
import { announceForA11y } from "~/lib/a11y";
|
||||||
|
|
||||||
const MODE = {
|
const MODE = {
|
||||||
|
|
@ -43,63 +38,8 @@ const rightButtonIconNames = {
|
||||||
|
|
||||||
const RECORDING_TIMEOUT = 59;
|
const RECORDING_TIMEOUT = 59;
|
||||||
|
|
||||||
// Speech-optimized profile (smaller files, good voice quality)
|
|
||||||
const recordingOptionsSpeech = {
|
|
||||||
...RecordingPresets.HIGH_QUALITY,
|
|
||||||
// Voice-friendly sample rate & bitrate
|
|
||||||
sampleRate: 22050,
|
|
||||||
numberOfChannels: 1,
|
|
||||||
bitRate: 24000,
|
|
||||||
ios: {
|
|
||||||
...RecordingPresets.HIGH_QUALITY.ios,
|
|
||||||
outputFormat: IOSOutputFormat.MPEG4AAC,
|
|
||||||
// Medium is enough for voice; final quality driven by bitRate above
|
|
||||||
audioQuality: AudioQuality.MEDIUM,
|
|
||||||
},
|
|
||||||
android: {
|
|
||||||
...RecordingPresets.HIGH_QUALITY.android,
|
|
||||||
outputFormat: "mpeg4",
|
|
||||||
audioEncoder: "aac",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Fallback profile (broader device compatibility if speech profile fails)
|
|
||||||
const recordingOptionsFallback = {
|
|
||||||
...RecordingPresets.HIGH_QUALITY,
|
|
||||||
sampleRate: 44100,
|
|
||||||
numberOfChannels: 1,
|
|
||||||
bitRate: 64000,
|
|
||||||
ios: {
|
|
||||||
...RecordingPresets.HIGH_QUALITY.ios,
|
|
||||||
outputFormat: IOSOutputFormat.MPEG4AAC,
|
|
||||||
audioQuality: AudioQuality.MAX,
|
|
||||||
},
|
|
||||||
android: {
|
|
||||||
...RecordingPresets.HIGH_QUALITY.android,
|
|
||||||
outputFormat: "mpeg4",
|
|
||||||
audioEncoder: "aac",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const activeOpacity = 0.7;
|
const activeOpacity = 0.7;
|
||||||
|
|
||||||
const withTimeout = (promise, ms = 10000) =>
|
|
||||||
new Promise((resolve, reject) => {
|
|
||||||
const id = setTimeout(
|
|
||||||
() => reject(new Error("Permission request timeout")),
|
|
||||||
ms,
|
|
||||||
);
|
|
||||||
promise
|
|
||||||
.then((v) => {
|
|
||||||
clearTimeout(id);
|
|
||||||
resolve(v);
|
|
||||||
})
|
|
||||||
.catch((e) => {
|
|
||||||
clearTimeout(id);
|
|
||||||
reject(e);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const ensureMicPermission = async () => {
|
const ensureMicPermission = async () => {
|
||||||
if (Platform.OS !== "android") {
|
if (Platform.OS !== "android") {
|
||||||
return { granted: true, status: RESULTS.UNAVAILABLE };
|
return { granted: true, status: RESULTS.UNAVAILABLE };
|
||||||
|
|
@ -150,11 +90,16 @@ export default React.memo(function ChatInput({
|
||||||
const { hasMessages } = useAlertState(["hasMessages"]);
|
const { hasMessages } = useAlertState(["hasMessages"]);
|
||||||
const autoFocus = !hasMessages;
|
const autoFocus = !hasMessages;
|
||||||
|
|
||||||
const [isRecording, setIsRecording] = useState(false);
|
|
||||||
const recorder = useAudioRecorder(recordingOptionsSpeech);
|
|
||||||
const [player, setPlayer] = useState(null);
|
const [player, setPlayer] = useState(null);
|
||||||
const requestingMicRef = useRef(false);
|
const requestingMicRef = useRef(false);
|
||||||
|
|
||||||
|
const {
|
||||||
|
isRecording: isVoiceRecording,
|
||||||
|
uri: recordingUri,
|
||||||
|
start: startVoiceRecorder,
|
||||||
|
stop: stopVoiceRecorder,
|
||||||
|
} = useVoiceRecorder();
|
||||||
|
|
||||||
// A11y: avoid repeated announcements while recording (e.g. every countdown tick)
|
// A11y: avoid repeated announcements while recording (e.g. every countdown tick)
|
||||||
const lastRecordingAnnouncementRef = useRef(null);
|
const lastRecordingAnnouncementRef = useRef(null);
|
||||||
|
|
||||||
|
|
@ -171,7 +116,11 @@ export default React.memo(function ChatInput({
|
||||||
}, [player]);
|
}, [player]);
|
||||||
|
|
||||||
const hasText = text.length > 0;
|
const hasText = text.length > 0;
|
||||||
const mode = isRecording ? MODE.RECORDING : hasText ? MODE.TEXT : MODE.EMPTY;
|
const mode = isVoiceRecording
|
||||||
|
? MODE.RECORDING
|
||||||
|
: hasText
|
||||||
|
? MODE.TEXT
|
||||||
|
: MODE.EMPTY;
|
||||||
|
|
||||||
const sendTextMessage = useCallback(async () => {
|
const sendTextMessage = useCallback(async () => {
|
||||||
if (!text) {
|
if (!text) {
|
||||||
|
|
@ -215,6 +164,18 @@ export default React.memo(function ChatInput({
|
||||||
}
|
}
|
||||||
requestingMicRef.current = true;
|
requestingMicRef.current = true;
|
||||||
try {
|
try {
|
||||||
|
console.log("[ChatInput] startRecording invoked", {
|
||||||
|
platform: Platform.OS,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (Platform.OS === "ios" && Device.isDevice === false) {
|
||||||
|
Alert.alert(
|
||||||
|
"Microphone indisponible",
|
||||||
|
"L'enregistrement audio n'est pas supporté sur le simulateur iOS.",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
console.log("Requesting microphone permission..");
|
console.log("Requesting microphone permission..");
|
||||||
if (Platform.OS === "android") {
|
if (Platform.OS === "android") {
|
||||||
const { granted, status } = await ensureMicPermission();
|
const { granted, status } = await ensureMicPermission();
|
||||||
|
|
@ -236,24 +197,8 @@ export default React.memo(function ChatInput({
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try {
|
// iOS microphone permission is handled inside useVoiceRecorder via expo-audio
|
||||||
await withTimeout(requestRecordingPermissionsAsync(), 10000);
|
|
||||||
} catch (permErr) {
|
|
||||||
console.log(
|
|
||||||
"Microphone permission request failed/timed out:",
|
|
||||||
permErr,
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
await setAudioModeAsync({
|
|
||||||
allowsRecording: true,
|
|
||||||
interruptionMode: "doNotMix",
|
|
||||||
playsInSilentMode: true,
|
|
||||||
interruptionModeAndroid: "doNotMix",
|
|
||||||
shouldRouteThroughEarpiece: false,
|
|
||||||
shouldPlayInBackground: true,
|
|
||||||
});
|
|
||||||
// stop playback
|
// stop playback
|
||||||
if (player !== null) {
|
if (player !== null) {
|
||||||
try {
|
try {
|
||||||
|
|
@ -262,27 +207,11 @@ export default React.memo(function ChatInput({
|
||||||
setPlayer(null);
|
setPlayer(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("Starting recording..");
|
|
||||||
await setAudioModeAsync({
|
|
||||||
allowsRecording: true,
|
|
||||||
interruptionMode: "doNotMix",
|
|
||||||
playsInSilentMode: true,
|
|
||||||
interruptionModeAndroid: "doNotMix",
|
|
||||||
shouldRouteThroughEarpiece: false,
|
|
||||||
shouldPlayInBackground: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Try speech-optimized settings first
|
console.log(
|
||||||
try {
|
"[ChatInput] startRecording delegating to useVoiceRecorder.start",
|
||||||
await recorder.prepareToRecordAsync(recordingOptionsSpeech);
|
);
|
||||||
} catch (optErr) {
|
await startVoiceRecorder();
|
||||||
console.log("Speech-optimized profile failed, falling back:", optErr);
|
|
||||||
await recorder.prepareToRecordAsync(recordingOptionsFallback);
|
|
||||||
}
|
|
||||||
recorder.record();
|
|
||||||
console.log("recording");
|
|
||||||
setIsRecording(true);
|
|
||||||
|
|
||||||
// Announce once when recording starts.
|
// Announce once when recording starts.
|
||||||
if (lastRecordingAnnouncementRef.current !== "started") {
|
if (lastRecordingAnnouncementRef.current !== "started") {
|
||||||
|
|
@ -291,82 +220,224 @@ export default React.memo(function ChatInput({
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("error while recording:", error);
|
console.log("error while recording:", error);
|
||||||
|
Sentry.captureException(error, {
|
||||||
|
tags: {
|
||||||
|
feature: "audio-message",
|
||||||
|
stage: "startRecording",
|
||||||
|
},
|
||||||
|
extra: {
|
||||||
|
platform: Platform.OS,
|
||||||
|
alertId,
|
||||||
|
recordingUri,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
announceForA11y("Échec du démarrage de l'enregistrement audio");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
console.log("Recording started");
|
console.log("[ChatInput] Recording started");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("Failed to start recording", err);
|
console.log("Failed to start recording", err);
|
||||||
|
Sentry.captureException(err, {
|
||||||
|
tags: {
|
||||||
|
feature: "audio-message",
|
||||||
|
stage: "startRecording-outer",
|
||||||
|
},
|
||||||
|
extra: {
|
||||||
|
platform: Platform.OS,
|
||||||
|
alertId,
|
||||||
|
recordingUri,
|
||||||
|
},
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
requestingMicRef.current = false;
|
requestingMicRef.current = false;
|
||||||
}
|
}
|
||||||
}, [player, recorder]);
|
}, [alertId, player, recordingUri, startVoiceRecorder]);
|
||||||
|
|
||||||
const stopRecording = useCallback(async () => {
|
const stopRecording = useCallback(async () => {
|
||||||
|
console.log("[ChatInput] stopRecording invoked", {
|
||||||
|
platform: Platform.OS,
|
||||||
|
isRecordingBefore: isVoiceRecording,
|
||||||
|
});
|
||||||
|
let uri = null;
|
||||||
try {
|
try {
|
||||||
await recorder.stop();
|
uri = await stopVoiceRecorder();
|
||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
// Do nothing -- already stopped/unloaded.
|
// Do nothing -- already stopped/unloaded.
|
||||||
|
console.log("[ChatInput] stopVoiceRecorder threw (ignored)", _error);
|
||||||
}
|
}
|
||||||
if (isRecording) {
|
const effectiveUri = uri || recordingUri;
|
||||||
setIsRecording(false);
|
console.log("[ChatInput] stopRecording completed", {
|
||||||
|
platform: Platform.OS,
|
||||||
|
isRecordingAfter: false,
|
||||||
|
recordingUri: effectiveUri,
|
||||||
|
});
|
||||||
|
if (isVoiceRecording) {
|
||||||
// Announce once when recording stops.
|
// Announce once when recording stops.
|
||||||
if (lastRecordingAnnouncementRef.current !== "stopped") {
|
if (lastRecordingAnnouncementRef.current !== "stopped") {
|
||||||
lastRecordingAnnouncementRef.current = "stopped";
|
lastRecordingAnnouncementRef.current = "stopped";
|
||||||
announceForA11y("Enregistrement arrêté");
|
announceForA11y("Enregistrement arrêté");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [recorder, isRecording]);
|
return effectiveUri;
|
||||||
|
}, [isVoiceRecording, recordingUri, stopVoiceRecorder]);
|
||||||
|
|
||||||
const recordedToSound = useCallback(async () => {
|
const recordedToSound = useCallback(
|
||||||
await setAudioModeAsync({
|
async (uriOverride) => {
|
||||||
allowsRecording: false,
|
console.log("[ChatInput] recordedToSound invoked", {
|
||||||
interruptionMode: "doNotMix",
|
platform: Platform.OS,
|
||||||
playsInSilentMode: true,
|
});
|
||||||
interruptionModeAndroid: "doNotMix",
|
try {
|
||||||
shouldRouteThroughEarpiece: false,
|
await setAudioModeAsync({
|
||||||
shouldPlayInBackground: true,
|
allowsRecording: false,
|
||||||
});
|
playsInSilentMode: true,
|
||||||
const status = recorder.getStatus();
|
interruptionMode: "doNotMix",
|
||||||
const url = status?.url;
|
interruptionModeAndroid: "doNotMix",
|
||||||
if (url) {
|
shouldRouteThroughEarpiece: false,
|
||||||
const _player = createAudioPlayer(url);
|
// Foreground-first: do not keep audio session alive in background.
|
||||||
setPlayer(_player);
|
shouldPlayInBackground: false,
|
||||||
}
|
});
|
||||||
}, [recorder]);
|
} catch (error) {
|
||||||
|
console.log(
|
||||||
|
"[ChatInput] Audio.setAudioModeAsync for playback failed",
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const uploadAudio = useCallback(async () => {
|
const url = uriOverride || recordingUri;
|
||||||
const { url } = recorder.getStatus();
|
console.log("[ChatInput] recordedToSound status after recording", {
|
||||||
const uri = url;
|
platform: Platform.OS,
|
||||||
if (!uri) {
|
url,
|
||||||
throw new Error("No recording URL available");
|
});
|
||||||
}
|
if (url) {
|
||||||
const fd = new FormData();
|
const _player = createAudioPlayer(url);
|
||||||
fd.append("data[alertId]", alertId);
|
setPlayer(_player);
|
||||||
fd.append("data[file]", {
|
console.log("[ChatInput] recordedToSound created player", {
|
||||||
uri,
|
hasPlayer: !!_player,
|
||||||
type: "audio/mp4",
|
});
|
||||||
name: "audioRecord.m4a",
|
}
|
||||||
});
|
},
|
||||||
await network.oaFilesKy.post("audio/upload", {
|
[recordingUri],
|
||||||
body: fd,
|
);
|
||||||
});
|
|
||||||
}, [alertId, recorder]);
|
const uploadAudio = useCallback(
|
||||||
|
async (uriOverride) => {
|
||||||
|
const rawUrl = uriOverride ?? recordingUri ?? null;
|
||||||
|
const uri =
|
||||||
|
Platform.OS === "ios" && rawUrl && !rawUrl.startsWith("file:")
|
||||||
|
? `file://${rawUrl}`
|
||||||
|
: rawUrl;
|
||||||
|
|
||||||
|
console.log("[ChatInput] uploadAudio invoked", {
|
||||||
|
platform: Platform.OS,
|
||||||
|
recordingUri,
|
||||||
|
rawUrl,
|
||||||
|
uri,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!uri) {
|
||||||
|
const error = new Error("No recording URL available");
|
||||||
|
console.error("[ChatInput] uploadAudio error: missing uri", error, {
|
||||||
|
platform: Platform.OS,
|
||||||
|
recordingUri,
|
||||||
|
});
|
||||||
|
Sentry.captureException(error, {
|
||||||
|
tags: {
|
||||||
|
feature: "audio-message",
|
||||||
|
stage: "uploadAudio",
|
||||||
|
},
|
||||||
|
extra: {
|
||||||
|
platform: Platform.OS,
|
||||||
|
recordingUri,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append("data[alertId]", alertId);
|
||||||
|
const fileField = {
|
||||||
|
uri,
|
||||||
|
// Keep Android behavior, but this remains valid for iOS (AAC in MP4 container).
|
||||||
|
type: "audio/mp4",
|
||||||
|
name: "audioRecord.m4a",
|
||||||
|
};
|
||||||
|
console.log("[ChatInput] uploadAudio FormData file field", fileField);
|
||||||
|
fd.append("data[file]", fileField);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await network.oaFilesKy.post("audio/upload", {
|
||||||
|
body: fd,
|
||||||
|
});
|
||||||
|
console.log("[ChatInput] uploadAudio response", {
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
} catch (error) {
|
||||||
|
const statusCode = error?.response?.status;
|
||||||
|
const statusText = error?.response?.statusText;
|
||||||
|
console.error("[ChatInput] uploadAudio network error", error, {
|
||||||
|
platform: Platform.OS,
|
||||||
|
statusCode,
|
||||||
|
statusText,
|
||||||
|
});
|
||||||
|
Sentry.captureException(error, {
|
||||||
|
tags: {
|
||||||
|
feature: "audio-message",
|
||||||
|
stage: "uploadAudio",
|
||||||
|
},
|
||||||
|
extra: {
|
||||||
|
platform: Platform.OS,
|
||||||
|
statusCode,
|
||||||
|
statusText,
|
||||||
|
recordingUri,
|
||||||
|
uri,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[alertId, recordingUri],
|
||||||
|
);
|
||||||
|
|
||||||
const sendRecording = useCallback(async () => {
|
const sendRecording = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
await stopRecording();
|
console.log("[ChatInput] sendRecording start", {
|
||||||
await recordedToSound();
|
platform: Platform.OS,
|
||||||
await uploadAudio();
|
});
|
||||||
|
const uri = await stopRecording();
|
||||||
|
await recordedToSound(uri);
|
||||||
|
await uploadAudio(uri);
|
||||||
|
|
||||||
// Keep focus stable: return focus to input after finishing recording flow.
|
// Keep focus stable: return focus to input after finishing recording flow.
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
textInputRef.current?.focus?.();
|
textInputRef.current?.focus?.();
|
||||||
}, 0);
|
}, 0);
|
||||||
|
console.log("[ChatInput] sendRecording completed successfully");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to send recording:", error);
|
const statusCode = error?.response?.status;
|
||||||
|
const statusText = error?.response?.statusText;
|
||||||
|
console.error("[ChatInput] Failed to send recording", error, {
|
||||||
|
platform: Platform.OS,
|
||||||
|
statusCode,
|
||||||
|
statusText,
|
||||||
|
});
|
||||||
|
Sentry.captureException(error, {
|
||||||
|
tags: {
|
||||||
|
feature: "audio-message",
|
||||||
|
stage: "sendRecording",
|
||||||
|
},
|
||||||
|
extra: {
|
||||||
|
platform: Platform.OS,
|
||||||
|
statusCode,
|
||||||
|
statusText,
|
||||||
|
alertId,
|
||||||
|
recordingUri,
|
||||||
|
},
|
||||||
|
});
|
||||||
announceForA11y("Échec de l'envoi de l'enregistrement audio");
|
announceForA11y("Échec de l'envoi de l'enregistrement audio");
|
||||||
}
|
}
|
||||||
}, [stopRecording, recordedToSound, uploadAudio]);
|
}, [alertId, recordingUri, stopRecording, recordedToSound, uploadAudio]);
|
||||||
|
|
||||||
const deleteRecording = useCallback(async () => {
|
const deleteRecording = useCallback(async () => {
|
||||||
await stopRecording();
|
await stopRecording();
|
||||||
|
|
@ -376,18 +447,16 @@ export default React.memo(function ChatInput({
|
||||||
}, [stopRecording]);
|
}, [stopRecording]);
|
||||||
|
|
||||||
const triggerMicrophoneClick = useCallback(async () => {
|
const triggerMicrophoneClick = useCallback(async () => {
|
||||||
if (isRecording) {
|
if (isVoiceRecording) {
|
||||||
await sendRecording();
|
await sendRecording();
|
||||||
} else {
|
} else {
|
||||||
await startRecording();
|
await startRecording();
|
||||||
}
|
}
|
||||||
}, [isRecording, startRecording, sendRecording]);
|
}, [isVoiceRecording, startRecording, sendRecording]);
|
||||||
|
|
||||||
const onRecordingCountDownComplete = useCallback(async () => {
|
const onRecordingCountDownComplete = useCallback(async () => {
|
||||||
await stopRecording();
|
|
||||||
await recordedToSound();
|
|
||||||
await sendRecording();
|
await sendRecording();
|
||||||
}, [sendRecording, stopRecording, recordedToSound]);
|
}, [sendRecording]);
|
||||||
|
|
||||||
// reset on alert change
|
// reset on alert change
|
||||||
const dataRef = useRef(null);
|
const dataRef = useRef(null);
|
||||||
|
|
@ -488,20 +557,20 @@ export default React.memo(function ChatInput({
|
||||||
accessibilityLabel={
|
accessibilityLabel={
|
||||||
hasText
|
hasText
|
||||||
? "Envoyer le message"
|
? "Envoyer le message"
|
||||||
: isRecording
|
: isVoiceRecording
|
||||||
? "Envoyer l'enregistrement audio"
|
? "Envoyer l'enregistrement audio"
|
||||||
: "Démarrer l'enregistrement audio"
|
: "Démarrer l'enregistrement audio"
|
||||||
}
|
}
|
||||||
accessibilityHint={
|
accessibilityHint={
|
||||||
hasText
|
hasText
|
||||||
? "Envoie le message."
|
? "Envoie le message."
|
||||||
: isRecording
|
: isVoiceRecording
|
||||||
? "Envoie l'enregistrement audio."
|
? "Envoie l'enregistrement audio."
|
||||||
: "Démarre l'enregistrement audio."
|
: "Démarre l'enregistrement audio."
|
||||||
}
|
}
|
||||||
accessibilityState={{
|
accessibilityState={{
|
||||||
disabled: false,
|
disabled: false,
|
||||||
...(isRecording ? { selected: true } : null),
|
...(isVoiceRecording ? { selected: true } : null),
|
||||||
}}
|
}}
|
||||||
onPress={hasText ? sendTextMessage : triggerMicrophoneClick}
|
onPress={hasText ? sendTextMessage : triggerMicrophoneClick}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
162
src/hooks/useVoiceRecorder.js
Normal file
162
src/hooks/useVoiceRecorder.js
Normal file
|
|
@ -0,0 +1,162 @@
|
||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import {
|
||||||
|
RecordingPresets,
|
||||||
|
requestRecordingPermissionsAsync,
|
||||||
|
setAudioModeAsync,
|
||||||
|
setIsAudioActiveAsync,
|
||||||
|
useAudioRecorder,
|
||||||
|
} from "expo-audio";
|
||||||
|
|
||||||
|
let hasLoggedAudioMode = false;
|
||||||
|
|
||||||
|
export default function useVoiceRecorder() {
|
||||||
|
const recorderRef = useRef(null);
|
||||||
|
const [isRecording, setIsRecording] = useState(false);
|
||||||
|
const [uri, setUri] = useState(null);
|
||||||
|
|
||||||
|
// NOTE: `expo-audio` doesn't export `AudioRecorder` as a runtime JS class.
|
||||||
|
// The supported API is `useAudioRecorder`, which returns a native-backed SharedObject.
|
||||||
|
const preset =
|
||||||
|
RecordingPresets?.HIGH_QUALITY || RecordingPresets?.LOW_QUALITY;
|
||||||
|
if (!preset) {
|
||||||
|
throw new Error(
|
||||||
|
"expo-audio RecordingPresets are not available; cannot start recording",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const recorder = useAudioRecorder({
|
||||||
|
...preset,
|
||||||
|
isMeteringEnabled: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
recorderRef.current = recorder;
|
||||||
|
return () => {
|
||||||
|
if (recorderRef.current === recorder) {
|
||||||
|
recorderRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [recorder]);
|
||||||
|
|
||||||
|
const cleanupRecording = useCallback(async () => {
|
||||||
|
const recorder = recorderRef.current;
|
||||||
|
if (recorder) {
|
||||||
|
try {
|
||||||
|
if (recorder.isRecording) {
|
||||||
|
await recorder.stop();
|
||||||
|
}
|
||||||
|
} catch (_e) {
|
||||||
|
// no-op
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setIsRecording(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const start = useCallback(async () => {
|
||||||
|
// Reset any previous recording before starting a new one
|
||||||
|
await cleanupRecording();
|
||||||
|
setUri(null);
|
||||||
|
|
||||||
|
const permission = await requestRecordingPermissionsAsync();
|
||||||
|
if (!permission?.granted) {
|
||||||
|
throw new Error("Microphone permission not granted");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure audio mode for recording (iOS & Android)
|
||||||
|
const recordingAudioMode = {
|
||||||
|
allowsRecording: true,
|
||||||
|
playsInSilentMode: true,
|
||||||
|
interruptionMode: "doNotMix",
|
||||||
|
interruptionModeAndroid: "doNotMix",
|
||||||
|
shouldRouteThroughEarpiece: false,
|
||||||
|
// Foreground-first: keep the audio session inactive in background.
|
||||||
|
shouldPlayInBackground: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!hasLoggedAudioMode) {
|
||||||
|
console.log("[useVoiceRecorder] audio mode set", recordingAudioMode);
|
||||||
|
hasLoggedAudioMode = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
await setAudioModeAsync(recordingAudioMode);
|
||||||
|
|
||||||
|
const prepareAndStart = async () => {
|
||||||
|
await setIsAudioActiveAsync(true).catch(() => {});
|
||||||
|
console.log("[useVoiceRecorder] preparing recorder");
|
||||||
|
await recorder.prepareToRecordAsync();
|
||||||
|
console.log("[useVoiceRecorder] starting recorder");
|
||||||
|
recorder.record();
|
||||||
|
setIsRecording(true);
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await prepareAndStart();
|
||||||
|
} catch (error) {
|
||||||
|
console.log("[useVoiceRecorder] recorder start failed", error);
|
||||||
|
|
||||||
|
// One controlled retry for iOS: reset the audio session and try once more.
|
||||||
|
try {
|
||||||
|
await cleanupRecording();
|
||||||
|
await setAudioModeAsync(recordingAudioMode);
|
||||||
|
await new Promise((r) => setTimeout(r, 150));
|
||||||
|
await prepareAndStart();
|
||||||
|
return;
|
||||||
|
} catch (_retryError) {
|
||||||
|
console.log("[useVoiceRecorder] recorder retry failed", _retryError);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (recorderRef.current?.isRecording) {
|
||||||
|
await recorderRef.current.stop();
|
||||||
|
}
|
||||||
|
} catch (_e) {
|
||||||
|
// ignore cleanup failures
|
||||||
|
} finally {
|
||||||
|
// keep recorder instance; hook will manage its lifecycle
|
||||||
|
setIsRecording(false);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}, [cleanupRecording, recorder]);
|
||||||
|
|
||||||
|
const stop = useCallback(async () => {
|
||||||
|
const recorder = recorderRef.current;
|
||||||
|
if (!recorder) {
|
||||||
|
setIsRecording(false);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await recorder.stop();
|
||||||
|
} catch (_e) {
|
||||||
|
// ignore errors from already-stopped/unloaded recordings
|
||||||
|
}
|
||||||
|
|
||||||
|
const recordingUri = recorder.uri;
|
||||||
|
setUri(recordingUri ?? null);
|
||||||
|
setIsRecording(false);
|
||||||
|
return recordingUri ?? null;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const reset = useCallback(() => {
|
||||||
|
setUri(null);
|
||||||
|
setIsRecording(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
const recorder = recorderRef.current;
|
||||||
|
if (recorder) {
|
||||||
|
if (recorder.isRecording) {
|
||||||
|
recorder.stop().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isRecording,
|
||||||
|
uri,
|
||||||
|
start,
|
||||||
|
stop,
|
||||||
|
reset,
|
||||||
|
};
|
||||||
|
}
|
||||||
16
yarn.lock
16
yarn.lock
|
|
@ -7066,7 +7066,6 @@ __metadata:
|
||||||
eventemitter3: "npm:^5.0.1"
|
eventemitter3: "npm:^5.0.1"
|
||||||
expo: "npm:~53.0.23"
|
expo: "npm:~53.0.23"
|
||||||
expo-audio: "npm:~0.4.9"
|
expo-audio: "npm:~0.4.9"
|
||||||
expo-av: "npm:~15.1.7"
|
|
||||||
expo-build-properties: "npm:~0.14.8"
|
expo-build-properties: "npm:~0.14.8"
|
||||||
expo-constants: "npm:~17.1.7"
|
expo-constants: "npm:~17.1.7"
|
||||||
expo-contacts: "npm:~14.2.5"
|
expo-contacts: "npm:~14.2.5"
|
||||||
|
|
@ -10594,21 +10593,6 @@ __metadata:
|
||||||
languageName: node
|
languageName: node
|
||||||
linkType: hard
|
linkType: hard
|
||||||
|
|
||||||
"expo-av@npm:~15.1.7":
|
|
||||||
version: 15.1.7
|
|
||||||
resolution: "expo-av@npm:15.1.7"
|
|
||||||
peerDependencies:
|
|
||||||
expo: "*"
|
|
||||||
react: "*"
|
|
||||||
react-native: "*"
|
|
||||||
react-native-web: "*"
|
|
||||||
peerDependenciesMeta:
|
|
||||||
react-native-web:
|
|
||||||
optional: true
|
|
||||||
checksum: 10/8f3055b68cac76b627116cf93a63bebdacb8c0d22f630f9fdae7dc74633a945d9a469421fce0f4c345c730eda0d039d78c88e59c09e2219bfde7e259d42981ba
|
|
||||||
languageName: node
|
|
||||||
linkType: hard
|
|
||||||
|
|
||||||
"expo-build-properties@npm:~0.14.8":
|
"expo-build-properties@npm:~0.14.8":
|
||||||
version: 0.14.8
|
version: 0.14.8
|
||||||
resolution: "expo-build-properties@npm:0.14.8"
|
resolution: "expo-build-properties@npm:0.14.8"
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue