import { createAudioPlayer, requestRecordingPermissionsAsync, setAudioModeAsync, } from "expo-audio"; export interface RecordingResult { uri: string; durationMs: number; } let currentPlayer: ReturnType | null = null; export async function requestPermissions(): Promise { const { status } = await requestRecordingPermissionsAsync(); return status === "granted"; } export async function playAudio( uri: string, onFinish?: () => void ): Promise { try { await stopPlayback(); await setAudioModeAsync({ playsInSilentMode: true, }); const player = createAudioPlayer(uri); currentPlayer = player; player.addListener("playbackStatusUpdate", (status) => { if (!status.playing && status.currentTime >= status.duration && status.duration > 0) { onFinish?.(); player.remove(); if (currentPlayer === player) currentPlayer = null; } }); player.play(); } catch (error) { console.error("Failed to play audio:", error); } } export async function stopPlayback(): Promise { if (currentPlayer) { try { currentPlayer.pause(); currentPlayer.remove(); } catch { // Ignore cleanup errors } currentPlayer = null; } } export async function encodeAudioToBase64(uri: string): Promise { const FileSystem = await import("expo-file-system"); const result = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64, }); return result; }