@siteed/audio-studio 3.2.1-beta.1 → 3.2.1-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/README.md +12 -1
- package/build/cjs/AudioStudio.types.js.map +1 -1
- package/build/cjs/useAudioRecorder.js +115 -93
- package/build/cjs/useAudioRecorder.js.map +1 -1
- package/build/cjs/utils/nativeRecordingOptions.js +13 -0
- package/build/cjs/utils/nativeRecordingOptions.js.map +1 -0
- package/build/cjs/utils/nativeRecordingOptions.test.js +30 -0
- package/build/cjs/utils/nativeRecordingOptions.test.js.map +1 -0
- package/build/esm/AudioStudio.types.js.map +1 -1
- package/build/esm/useAudioRecorder.js +115 -93
- package/build/esm/useAudioRecorder.js.map +1 -1
- package/build/esm/utils/nativeRecordingOptions.js +10 -0
- package/build/esm/utils/nativeRecordingOptions.js.map +1 -0
- package/build/esm/utils/nativeRecordingOptions.test.js +28 -0
- package/build/esm/utils/nativeRecordingOptions.test.js.map +1 -0
- package/build/types/AudioStudio.types.d.ts +19 -5
- package/build/types/AudioStudio.types.d.ts.map +1 -1
- package/build/types/useAudioRecorder.d.ts +2 -1
- package/build/types/useAudioRecorder.d.ts.map +1 -1
- package/build/types/utils/nativeRecordingOptions.d.ts +28 -0
- package/build/types/utils/nativeRecordingOptions.d.ts.map +1 -0
- package/build/types/utils/nativeRecordingOptions.test.d.ts +2 -0
- package/build/types/utils/nativeRecordingOptions.test.d.ts.map +1 -0
- package/package.json +2 -1
- package/plugin/build/index.cjs +79 -47
- package/plugin/build/index.d.cts +15 -0
- package/plugin/build/index.js +79 -47
- package/plugin/src/index.test.ts +78 -0
- package/plugin/src/index.ts +141 -59
- package/plugin/tsconfig.json +6 -1
- package/src/AudioStudio.types.ts +27 -5
- package/src/useAudioRecorder.tsx +161 -126
- package/src/utils/nativeRecordingOptions.test.ts +29 -0
- package/src/utils/nativeRecordingOptions.ts +20 -0
|
@@ -1 +1 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AE,KAAK,CACT,IAAI,UAAU,iDAAiD,CAClE,CAAA;YACL,CAAC;QACL,CAAC,CAAC,CAAA;QAEF,OAAO,GAAG,EAAE;YACR,MAAM,EAAE,KAAK,CACT,IAAI,UAAU,4CAA4C,CAC7D,CAAA;YACD,YAAY,CAAC,MAAM,EAAE,CAAA;QACzB,CAAC,CAAA;IACL,CAAC,EAAE,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAA,CAAC,gDAAgD;IAEzE,OAAO;QACH,gBAAgB;QAChB,cAAc;QACd,aAAa;QACb,cAAc;QACd,eAAe;QACf,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC/C,CAAA;AACL,CAAC","sourcesContent":["// src/useAudioRecorder.ts\nimport { EventSubscription, Platform } from 'expo-modules-core'\nimport { useCallback, useEffect, useReducer, useRef, useId } from 'react'\n\nimport { AudioAnalysis } from './AudioAnalysis/AudioAnalysis.types'\nimport { audioDeviceManager } from './AudioDeviceManager'\nimport {\n AudioDataEvent,\n AudioRecording,\n AudioStreamStatus,\n CompressionInfo,\n ConsoleLike,\n MaxDurationReachedEvent,\n RecordingConfig,\n StartRecordingResult,\n} from './AudioStudio.types'\nimport AudioStudioModule from './AudioStudioModule'\nimport { validateRecordingConfig } from './constants/platformLimitations'\nimport {\n addAudioAnalysisListener,\n addAudioEventListener,\n AudioEventPayload,\n addMaxDurationReachedListener,\n addRecordingInterruptionListener,\n} from './events'\nimport { cleanNativeOptions } from './utils/cleanNativeOptions'\n\nexport interface UseAudioRecorderProps {\n logger?: ConsoleLike\n audioWorkletUrl?: string\n featuresExtratorUrl?: string\n}\n\nexport interface UseAudioRecorderState {\n prepareRecording: (_: RecordingConfig) => Promise<void>\n startRecording: (_: RecordingConfig) => Promise<StartRecordingResult>\n stopRecording: () => Promise<AudioRecording>\n pauseRecording: () => Promise<void>\n resumeRecording: () => Promise<void>\n isRecording: boolean\n isPaused: boolean\n durationMs: number\n size: number\n compression?: CompressionInfo\n analysisData?: AudioAnalysis\n maxDurationMs?: number\n maxDurationReached?: boolean\n}\n\ninterface RecorderReducerState {\n isRecording: boolean\n isPaused: boolean\n durationMs: number\n size: number\n compression?: CompressionInfo\n analysisData?: AudioAnalysis\n maxDurationMs?: number\n maxDurationReached?: boolean\n}\n\ntype RecorderAction =\n | { type: 'START' | 'STOP' | 'PAUSE' | 'RESUME' }\n | {\n type: 'UPDATE_RECORDING_STATE'\n payload: {\n isRecording: boolean\n isPaused: boolean\n }\n }\n | {\n type: 'UPDATE_STATUS'\n payload: {\n durationMs: number\n size: number\n compression?: CompressionInfo\n maxDurationMs?: number\n maxDurationReached?: boolean\n }\n }\n | {\n type: 'MAX_DURATION_REACHED'\n payload: MaxDurationReachedEvent\n }\n | { type: 'UPDATE_ANALYSIS'; payload: AudioAnalysis }\n\nconst defaultAnalysis: AudioAnalysis = {\n segmentDurationMs: 100,\n bitDepth: 32,\n numberOfChannels: 1,\n durationMs: 0,\n sampleRate: 44100,\n samples: 0,\n dataPoints: [],\n rmsRange: {\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n },\n amplitudeRange: {\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n },\n extractionTimeMs: 0,\n}\n\nfunction audioRecorderReducer(\n state: RecorderReducerState,\n action: RecorderAction\n): RecorderReducerState {\n switch (action.type) {\n case 'START':\n return {\n ...state,\n isRecording: true,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n analysisData: defaultAnalysis,\n maxDurationMs: undefined,\n maxDurationReached: false,\n }\n case 'STOP':\n return {\n ...state,\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n analysisData: undefined,\n // Preserve max-duration state after stop so UI and agentic\n // validation can explain why recording ended. START resets it.\n }\n case 'PAUSE':\n return { ...state, isPaused: true, isRecording: false }\n case 'RESUME':\n return { ...state, isPaused: false, isRecording: true }\n case 'UPDATE_RECORDING_STATE':\n return {\n ...state,\n isPaused: action.payload.isPaused,\n isRecording: action.payload.isRecording,\n }\n case 'UPDATE_STATUS': {\n const newState = {\n ...state,\n durationMs: action.payload.durationMs,\n size: action.payload.size,\n compression: action.payload.compression\n ? {\n size: action.payload.compression.size,\n mimeType: action.payload.compression.mimeType,\n bitrate: action.payload.compression.bitrate,\n format: action.payload.compression.format,\n }\n : undefined,\n maxDurationMs: action.payload.maxDurationMs,\n maxDurationReached: action.payload.maxDurationReached,\n }\n return newState\n }\n case 'MAX_DURATION_REACHED':\n return {\n ...state,\n maxDurationMs: action.payload.maxDurationMs,\n maxDurationReached: true,\n }\n case 'UPDATE_ANALYSIS':\n return {\n ...state,\n analysisData: action.payload,\n }\n default:\n return state\n }\n}\n\ninterface HandleAudioAnalysisProps {\n analysis: AudioAnalysis\n visualizationDuration: number\n}\n\nfunction shouldKeepFullAnalysis(config?: RecordingConfig | null): boolean {\n return config?.keepFullAnalysis !== false\n}\n\nexport function useAudioRecorder({\n logger,\n audioWorkletUrl,\n featuresExtratorUrl,\n}: UseAudioRecorderProps = {}): UseAudioRecorderState {\n // Initialize AudioDeviceManager with logger (once)\n if (logger) {\n audioDeviceManager.setLogger(logger)\n }\n const [state, dispatch] = useReducer(audioRecorderReducer, {\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n analysisData: undefined,\n maxDurationMs: undefined,\n maxDurationReached: false,\n })\n\n const startResultRef = useRef<StartRecordingResult | null>(null)\n\n const analysisListenerRef = useRef<EventSubscription | null>(null)\n // analysisRef is the current analysis data (last 10 seconds by default)\n const analysisRef = useRef<AudioAnalysis>({ ...defaultAnalysis })\n // fullAnalysisRef is the full analysis data (all data points)\n const fullAnalysisRef = useRef<AudioAnalysis>({\n ...defaultAnalysis,\n })\n\n // Instantiate the module for web with URLs\n const audioStudio =\n Platform.OS === 'web'\n ? AudioStudioModule({\n audioWorkletUrl,\n featuresExtratorUrl,\n logger,\n })\n : AudioStudioModule\n\n const onAudioStreamRef = useRef<\n ((_: AudioDataEvent) => Promise<void>) | null\n >(null)\n\n const stateRef = useRef({\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined as CompressionInfo | undefined,\n maxDurationMs: undefined as number | undefined,\n maxDurationReached: false,\n })\n\n const recordingConfigRef = useRef<RecordingConfig | null>(null)\n const maxDurationHandledRef = useRef(false)\n\n // Generate unique instance ID for debugging\n const instanceId = useId().replace(/:/g, '').slice(0, 5)\n\n const handleAudioAnalysis = useCallback(\n async ({\n analysis,\n visualizationDuration,\n }: HandleAudioAnalysisProps) => {\n const savedAnalysisData = analysisRef.current || {\n ...defaultAnalysis,\n }\n\n const maxDuration = visualizationDuration\n\n logger?.debug(\n `[handleAudioAnalysis] Received audio analysis: maxDuration=${maxDuration} analysis.dataPoints=${analysis.dataPoints.length} analysisData.dataPoints=${savedAnalysisData.dataPoints.length}`\n )\n\n // Combine data points\n const combinedDataPoints = [\n ...savedAnalysisData.dataPoints,\n ...analysis.dataPoints,\n ]\n\n const keepFullAnalysis = shouldKeepFullAnalysis(\n recordingConfigRef.current\n )\n const fullCombinedDataPoints = keepFullAnalysis\n ? [\n ...(fullAnalysisRef.current?.dataPoints ?? []),\n ...analysis.dataPoints,\n ]\n : undefined\n\n // Calculate the new duration\n // The number of segments is based on how many segments of segmentDurationMs can fit in visualizationDuration\n const numberOfSegments = Math.ceil(\n visualizationDuration / analysis.segmentDurationMs\n )\n // maxDataPoints should be the number of data points, not milliseconds\n const maxDataPoints = numberOfSegments\n\n logger?.debug(\n `[handleAudioAnalysis] Combined data points before trimming: numberOfSegments=${numberOfSegments} visualizationDuration=${visualizationDuration} combinedDataPointsLength=${combinedDataPoints.length} vs maxDataPoints=${maxDataPoints}`\n )\n\n // Trim data points to keep within the maximum number of data points\n if (combinedDataPoints.length > maxDataPoints) {\n combinedDataPoints.splice(\n 0,\n combinedDataPoints.length - maxDataPoints\n )\n }\n\n // Keep the full data points when requested for stopRecording().analysisData.\n if (keepFullAnalysis && fullCombinedDataPoints) {\n fullAnalysisRef.current = {\n ...fullAnalysisRef.current,\n dataPoints: fullCombinedDataPoints,\n }\n fullAnalysisRef.current.durationMs =\n fullCombinedDataPoints.length * analysis.segmentDurationMs\n }\n savedAnalysisData.dataPoints = combinedDataPoints\n savedAnalysisData.bitDepth =\n analysis.bitDepth || savedAnalysisData.bitDepth\n savedAnalysisData.durationMs =\n combinedDataPoints.length * analysis.segmentDurationMs\n\n // Update amplitude range\n const newMin = Math.min(\n savedAnalysisData.amplitudeRange.min,\n analysis.amplitudeRange.min\n )\n const newMax = Math.max(\n savedAnalysisData.amplitudeRange.max,\n analysis.amplitudeRange.max\n )\n\n savedAnalysisData.amplitudeRange = {\n min: newMin,\n max: newMax,\n }\n if (keepFullAnalysis) {\n fullAnalysisRef.current.amplitudeRange = {\n min: newMin,\n max: newMax,\n }\n }\n\n logger?.debug(\n `[handleAudioAnalysis] Updated analysis data: durationMs=${savedAnalysisData.durationMs}`,\n { dataPoints: savedAnalysisData.dataPoints.length }\n )\n\n // Call the onAudioAnalysis callback if it exists in the recording config\n if (recordingConfigRef.current?.onAudioAnalysis) {\n recordingConfigRef.current\n .onAudioAnalysis(analysis)\n .catch((error) => {\n logger?.warn(`Error processing audio analysis:`, error)\n })\n }\n\n // Update the ref\n analysisRef.current = savedAnalysisData\n\n // Dispatch the updated analysis data to state to trigger re-render\n dispatch({\n type: 'UPDATE_ANALYSIS',\n payload: { ...savedAnalysisData },\n })\n },\n [dispatch]\n )\n\n const handleAudioEvent = useCallback(\n async (eventData: AudioEventPayload) => {\n const {\n fileUri,\n deltaSize,\n totalSize,\n lastEmittedSize,\n position,\n streamUuid,\n encoded,\n pcmFloat32,\n mimeType,\n buffer,\n compression,\n } = eventData\n logger?.debug(`[handleAudioEvent] Received audio event:`, {\n fileUri,\n deltaSize,\n totalSize,\n position,\n mimeType,\n lastEmittedSize,\n streamUuid,\n encodedLength: encoded?.length,\n compression,\n })\n if (deltaSize === 0) {\n // Ignore packet with no data\n return\n }\n try {\n // Coming from native ( ios / android ) otherwise buffer is set\n if (Platform.OS !== 'web') {\n const compressionPayload =\n compression && startResultRef.current?.compression\n ? {\n data: compression.data,\n size: compression.totalSize,\n mimeType:\n startResultRef.current.compression\n ?.mimeType,\n bitrate:\n startResultRef.current.compression\n ?.bitrate,\n format: startResultRef.current.compression\n ?.format,\n }\n : undefined\n if (pcmFloat32 != null) {\n // Android new arch delivers Float32Array; iOS delivers number[] — normalize both\n const float32 =\n pcmFloat32 instanceof Float32Array\n ? pcmFloat32\n : new Float32Array(pcmFloat32 as number[])\n onAudioStreamRef.current?.({\n data: float32,\n streamFormat: 'float32',\n position,\n fileUri,\n eventDataSize: deltaSize,\n totalSize,\n compression: compressionPayload,\n })\n } else {\n if (!encoded) {\n logger?.error(`Encoded audio data is missing`)\n throw new Error('Encoded audio data is missing')\n }\n onAudioStreamRef.current?.({\n data: encoded,\n position,\n fileUri,\n eventDataSize: deltaSize,\n totalSize,\n compression: compressionPayload,\n })\n }\n } else if (buffer) {\n // Coming from web\n const webEvent: AudioDataEvent = {\n data: buffer,\n position,\n fileUri,\n eventDataSize: deltaSize,\n totalSize,\n compression:\n compression && startResultRef.current?.compression\n ? {\n data: compression.data,\n size: compression.totalSize,\n mimeType:\n startResultRef.current.compression\n ?.mimeType,\n bitrate:\n startResultRef.current.compression\n ?.bitrate,\n format: startResultRef.current.compression\n ?.format,\n }\n : undefined,\n }\n onAudioStreamRef.current?.(webEvent)\n logger?.debug(\n `[handleAudioEvent] Audio data sent to onAudioStream`,\n webEvent\n )\n }\n } catch (error) {\n logger?.error(`Error processing audio event:`, error)\n }\n },\n []\n )\n\n const handleMaxDurationReached = useCallback(\n async (event: MaxDurationReachedEvent) => {\n if (maxDurationHandledRef.current) {\n return\n }\n\n maxDurationHandledRef.current = true\n const config = recordingConfigRef.current\n const callbackEvent: MaxDurationReachedEvent = {\n ...event,\n autoStopped:\n event.autoStopped || !!config?.autoStopOnMaxDuration,\n }\n\n stateRef.current.maxDurationMs = callbackEvent.maxDurationMs\n stateRef.current.maxDurationReached = true\n dispatch({\n type: 'MAX_DURATION_REACHED',\n payload: callbackEvent,\n })\n\n try {\n config?.onMaxDurationReached?.(callbackEvent)\n } catch (error) {\n logger?.error(`Error in max duration callback:`, error)\n }\n\n const finishStoppedState = () => {\n if (analysisListenerRef.current) {\n analysisListenerRef.current.remove()\n analysisListenerRef.current = null\n }\n onAudioStreamRef.current = null\n stateRef.current.isRecording = false\n stateRef.current.isPaused = false\n dispatch({ type: 'STOP' })\n }\n\n const waitForPlatformAutoStop = async () => {\n const timeoutMs = 3000\n const startedAt = Date.now()\n let lastStatus: AudioStreamStatus | undefined\n\n while (Date.now() - startedAt < timeoutMs) {\n await new Promise((resolve) => setTimeout(resolve, 50))\n try {\n const currentStatus: AudioStreamStatus =\n audioStudio.status()\n lastStatus = currentStatus\n if (\n !currentStatus.isRecording &&\n !currentStatus.isPaused\n ) {\n finishStoppedState()\n return\n }\n } catch (error) {\n logger?.warn(\n `Error checking status after max duration auto-stop:`,\n error\n )\n break\n }\n }\n\n if (\n lastStatus &&\n (lastStatus.isRecording || lastStatus.isPaused)\n ) {\n try {\n await audioStudio.stopRecording()\n } catch (error) {\n logger?.warn(\n `Error completing max duration auto-stop fallback:`,\n error\n )\n }\n }\n // At this point platform-owned auto-stop did not settle cleanly.\n // Clear hook state so the UI does not stay stuck as recording.\n finishStoppedState()\n }\n\n // Only the original event tells us whether the platform already\n // owns auto-stop. Keep stream callbacks alive until status confirms\n // stop completion so native final audio flushes can still reach JS.\n if (event.autoStopped && stateRef.current.isRecording) {\n await waitForPlatformAutoStop()\n return\n }\n\n if (\n config?.autoStopOnMaxDuration &&\n !event.autoStopped &&\n stateRef.current.isRecording\n ) {\n try {\n await audioStudio.stopRecording()\n finishStoppedState()\n } catch (error) {\n logger?.error(`Error auto-stopping on max duration:`, error)\n }\n }\n },\n [audioStudio, dispatch, logger]\n )\n\n const checkStatus = useCallback(async () => {\n try {\n const status: AudioStreamStatus = audioStudio.status()\n logger?.debug(\n `Status: paused: ${status.isPaused} isRecording: ${status.isRecording} durationMs: ${status.durationMs} size: ${status.size}`,\n status.compression\n )\n\n if (\n status.maxDurationReached === true &&\n status.maxDurationMs != null &&\n !stateRef.current.maxDurationReached\n ) {\n await handleMaxDurationReached({\n durationMs: status.durationMs,\n maxDurationMs: status.maxDurationMs,\n overrunMs: Math.max(\n 0,\n status.durationMs - status.maxDurationMs\n ),\n autoStopped: false,\n })\n }\n\n // Only dispatch if values actually changed\n if (\n status.isRecording !== stateRef.current.isRecording ||\n status.isPaused !== stateRef.current.isPaused\n ) {\n stateRef.current.isRecording = status.isRecording\n stateRef.current.isPaused = status.isPaused\n dispatch({\n type: 'UPDATE_RECORDING_STATE',\n payload: {\n isRecording: status.isRecording,\n isPaused: status.isPaused,\n },\n })\n }\n\n if (\n status.durationMs !== stateRef.current.durationMs ||\n status.size !== stateRef.current.size ||\n status.maxDurationMs !== stateRef.current.maxDurationMs ||\n status.maxDurationReached !==\n stateRef.current.maxDurationReached\n ) {\n stateRef.current.durationMs = status.durationMs\n stateRef.current.size = status.size\n stateRef.current.compression = status.compression\n stateRef.current.maxDurationMs = status.maxDurationMs\n stateRef.current.maxDurationReached =\n status.maxDurationReached ?? false\n dispatch({\n type: 'UPDATE_STATUS',\n payload: {\n durationMs: status.durationMs,\n size: status.size,\n compression: status.compression,\n maxDurationMs: status.maxDurationMs,\n maxDurationReached: status.maxDurationReached,\n },\n })\n }\n } catch (error) {\n logger?.error(`Error getting status:`, error)\n }\n }, [audioStudio, handleMaxDurationReached, logger])\n\n // Update ref when state changes\n useEffect(() => {\n stateRef.current = {\n isRecording: state.isRecording,\n isPaused: state.isPaused,\n durationMs: state.durationMs,\n size: state.size,\n compression: state.compression,\n maxDurationMs: state.maxDurationMs,\n maxDurationReached: state.maxDurationReached ?? false,\n }\n }, [\n state.isRecording,\n state.isPaused,\n state.durationMs,\n state.size,\n state.compression,\n state.maxDurationMs,\n state.maxDurationReached,\n ])\n\n const startRecording = useCallback(\n async (recordingOptions: RecordingConfig) => {\n // Validate the encoding configuration\n const validationResult = validateRecordingConfig({\n encoding: recordingOptions.encoding,\n })\n\n // Log warnings if any\n if (validationResult.warnings.length > 0) {\n validationResult.warnings.forEach((warning) => {\n logger?.warn(warning)\n })\n }\n\n // Update recording options with validated values\n const validatedOptions = {\n ...recordingOptions,\n encoding: validationResult.encoding,\n }\n\n recordingConfigRef.current = validatedOptions\n maxDurationHandledRef.current = false\n logger?.debug(\n `start recording with validated config`,\n validatedOptions\n )\n\n analysisRef.current = { ...defaultAnalysis } // Reset analysis data\n fullAnalysisRef.current = { ...defaultAnalysis }\n const {\n onAudioStream,\n onRecordingInterrupted,\n onMaxDurationReached,\n onAudioAnalysis,\n keepFullAnalysis: _keepFullAnalysis,\n ...options\n } = validatedOptions\n const { enableProcessing } = options\n\n const maxRecentDataDuration = 10000 // TODO compute maxRecentDataDuration based on screen dimensions\n if (typeof onAudioStream === 'function') {\n onAudioStreamRef.current = onAudioStream\n } else {\n logger?.warn(`onAudioStream is not a function`, onAudioStream)\n onAudioStreamRef.current = null\n }\n // Strip undefined values and functions that can't cross the native bridge\n const cleanOptions = cleanNativeOptions(options)\n const startResult: StartRecordingResult =\n await audioStudio.startRecording(cleanOptions)\n dispatch({ type: 'START' })\n\n startResultRef.current = startResult\n\n if (enableProcessing) {\n logger?.debug(`Enabling audio analysis listener`)\n const listener = addAudioAnalysisListener(\n async (analysisData) => {\n try {\n await handleAudioAnalysis({\n analysis: analysisData,\n visualizationDuration: maxRecentDataDuration,\n })\n } catch (error) {\n logger?.warn(\n `Error processing audio analysis:`,\n error\n )\n }\n }\n )\n\n analysisListenerRef.current = listener\n }\n\n return startResult\n },\n [handleAudioAnalysis, dispatch]\n )\n\n const prepareRecording = useCallback(\n async (recordingOptions: RecordingConfig) => {\n recordingConfigRef.current = recordingOptions\n logger?.debug(`preparing recording`, recordingOptions)\n\n analysisRef.current = { ...defaultAnalysis } // Reset analysis data\n fullAnalysisRef.current = { ...defaultAnalysis }\n const {\n onAudioStream,\n onRecordingInterrupted,\n onMaxDurationReached,\n onAudioAnalysis,\n keepFullAnalysis: _keepFullAnalysis,\n ...options\n } = recordingOptions\n\n // Store onAudioStream for later use when recording starts\n if (typeof onAudioStream === 'function') {\n onAudioStreamRef.current = onAudioStream\n } else {\n logger?.warn(`onAudioStream is not a function`, onAudioStream)\n onAudioStreamRef.current = null\n }\n\n // Strip undefined values and functions that can't cross the native bridge\n const cleanOptions = cleanNativeOptions(options)\n // Call the native prepareRecording method\n await audioStudio.prepareRecording(cleanOptions)\n logger?.debug(`recording prepared successfully`)\n },\n []\n )\n\n const stopRecording = useCallback(async () => {\n logger?.debug(`stoping recording`)\n\n const stopResult: AudioRecording = await audioStudio.stopRecording()\n if (shouldKeepFullAnalysis(recordingConfigRef.current)) {\n stopResult.analysisData = fullAnalysisRef.current\n } else {\n // `keepFullAnalysis` is a hook-level retention policy. If a platform\n // starts returning native analysisData in the future, keep opt-out\n // semantics explicit and avoid leaking a full history here.\n delete stopResult.analysisData\n }\n\n if (analysisListenerRef.current) {\n analysisListenerRef.current.remove()\n analysisListenerRef.current = null\n }\n onAudioStreamRef.current = null\n\n // Note: We deliberately DON'T clear recordingConfigRef here to preserve interruption callback\n logger?.debug(`recording stopped`, stopResult)\n maxDurationHandledRef.current = false\n dispatch({ type: 'STOP' })\n return stopResult\n }, [dispatch])\n\n const pauseRecording = useCallback(async () => {\n logger?.debug(`pause recording`)\n const pauseResult = await audioStudio.pauseRecording()\n dispatch({ type: 'PAUSE' })\n return pauseResult\n }, [dispatch])\n\n const resumeRecording = useCallback(async () => {\n logger?.debug(`resume recording`)\n const resumeResult = await audioStudio.resumeRecording()\n dispatch({ type: 'RESUME' })\n return resumeResult\n }, [dispatch])\n\n useEffect(() => {\n const subscription = addMaxDurationReachedListener(async (event) => {\n await handleMaxDurationReached(event)\n })\n\n return () => {\n subscription.remove()\n }\n }, [handleMaxDurationReached])\n\n useEffect(() => {\n let intervalId: ReturnType<typeof setInterval> | undefined\n\n if (state.isRecording || state.isPaused) {\n // Immediately check status when starting\n checkStatus()\n\n // Start interval\n intervalId = setInterval(checkStatus, 1000)\n }\n\n return () => {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = undefined\n }\n }\n }, [checkStatus, state.isRecording, state.isPaused])\n\n useEffect(() => {\n logger?.debug(`Registering audio event listener`)\n const subscribeAudio = addAudioEventListener(handleAudioEvent)\n\n logger?.debug(\n `Subscribed to audio event listener and analysis listener`,\n {\n subscribeAudio,\n }\n )\n\n return () => {\n logger?.debug(`Removing audio event listener`)\n subscribeAudio.remove()\n }\n }, [handleAudioEvent, handleAudioAnalysis])\n\n useEffect(() => {\n // Add event subscription for recording interruptions\n logger?.debug(\n `Setting up recording interruption listener [${instanceId}]`\n )\n\n const subscription = addRecordingInterruptionListener((event) => {\n logger?.debug(\n `[${instanceId}] Received recording interruption event:`,\n event\n )\n\n // Handle device disconnection for UI updates\n if (event.reason === 'deviceDisconnected') {\n logger?.debug(\n `[${instanceId}] Device disconnected - temporarily hiding last device from UI`\n )\n\n // Get current device list before the native layer updates\n const currentDevices = audioDeviceManager.getRawDevices()\n\n // Wait a moment for native layer to update, then compare\n setTimeout(async () => {\n try {\n // Get updated devices without notifying yet\n const updatedDevices =\n await audioDeviceManager.getAvailableDevices({\n refresh: true,\n })\n\n // Find missing devices by comparing lists\n const missingDevices = currentDevices.filter(\n (oldDevice) =>\n !updatedDevices.some(\n (newDevice) => newDevice.id === oldDevice.id\n )\n )\n\n if (missingDevices.length > 0) {\n // Mark all missing devices as disconnected (silently)\n missingDevices.forEach((missingDevice) => {\n logger?.debug(\n `[${instanceId}] Confirmed disconnected device: ${missingDevice.name} (${missingDevice.id})`\n )\n audioDeviceManager.markDeviceAsDisconnected(\n missingDevice.id,\n false\n )\n })\n }\n\n // Notify listeners once with the final filtered state\n audioDeviceManager.notifyListeners()\n } catch (error) {\n logger?.warn(\n `[${instanceId}] Error in delayed device disconnection handling:`,\n error\n )\n }\n }, 500) // 500ms delay to let native layer update\n } else if (event.reason === 'deviceConnected') {\n // Device reconnected - force refresh to show it immediately\n logger?.debug(\n `[${instanceId}] Device connected, forcing refresh`\n )\n audioDeviceManager.forceRefreshDevices()\n }\n\n // Check if we have a callback configured\n logger?.debug(\n `[${instanceId}] recordingConfigRef.current exists:`,\n !!recordingConfigRef.current\n )\n\n if (recordingConfigRef.current?.onRecordingInterrupted) {\n try {\n logger?.debug(\n `[${instanceId}] Calling recording interruption callback`\n )\n recordingConfigRef.current.onRecordingInterrupted(event)\n } catch (error) {\n logger?.error(\n `[${instanceId}] Error in recording interruption callback:`,\n error\n )\n }\n } else {\n logger?.debug(\n `[${instanceId}] No recording interruption callback configured`\n )\n }\n })\n\n return () => {\n logger?.debug(\n `[${instanceId}] Removing recording interruption listener`\n )\n subscription.remove()\n }\n }, [instanceId, logger]) // Include instanceId and logger in dependencies\n\n return {\n prepareRecording,\n startRecording,\n stopRecording,\n pauseRecording,\n resumeRecording,\n isPaused: state.isPaused,\n isRecording: state.isRecording,\n durationMs: state.durationMs,\n size: state.size,\n compression: state.compression,\n analysisData: state.analysisData,\n maxDurationMs: state.maxDurationMs,\n maxDurationReached: state.maxDurationReached,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useAudioRecorder.js","sourceRoot":"","sources":["../../src/useAudioRecorder.tsx"],"names":[],"mappings":";;;;;AAyOA,4CAmxBC;AA5/BD,0BAA0B;AAC1B,yDAA+D;AAC/D,iCAAyE;AAGzE,6DAAyD;AAYzD,4EAAmD;AACnD,yEAAyE;AACzE,qCAMi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,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;KACjD,CAAA;AACL,CAAC","sourcesContent":["// src/useAudioRecorder.ts\nimport { EventSubscription, Platform } from 'expo-modules-core'\nimport { useCallback, useEffect, useReducer, useRef, useId } from 'react'\n\nimport { AudioAnalysis } from './AudioAnalysis/AudioAnalysis.types'\nimport { audioDeviceManager } from './AudioDeviceManager'\nimport {\n AudioDataEvent,\n AudioRecording,\n AudioStreamStatus,\n CompressionInfo,\n ConsoleLike,\n MaxDurationReachedEvent,\n RecordingConfig,\n RecordingStopReason,\n StartRecordingResult,\n} from './AudioStudio.types'\nimport AudioStudioModule from './AudioStudioModule'\nimport { validateRecordingConfig } from './constants/platformLimitations'\nimport {\n addAudioAnalysisListener,\n addAudioEventListener,\n AudioEventPayload,\n addMaxDurationReachedListener,\n addRecordingInterruptionListener,\n} from './events'\nimport { createNativeRecordingOptions } from './utils/nativeRecordingOptions'\n\nexport interface UseAudioRecorderProps {\n logger?: ConsoleLike\n audioWorkletUrl?: string\n featuresExtratorUrl?: string\n}\n\nexport interface UseAudioRecorderState {\n prepareRecording: (_: RecordingConfig) => Promise<void>\n startRecording: (_: RecordingConfig) => Promise<StartRecordingResult>\n stopRecording: () => Promise<AudioRecording>\n pauseRecording: () => Promise<void>\n resumeRecording: () => Promise<void>\n isRecording: boolean\n isPaused: boolean\n durationMs: number\n size: number\n compression?: CompressionInfo\n analysisData?: AudioAnalysis\n maxDurationMs?: number\n maxDurationReached?: boolean\n lastRecordingReason?: RecordingStopReason\n}\n\ninterface RecorderReducerState {\n isRecording: boolean\n isPaused: boolean\n durationMs: number\n size: number\n compression?: CompressionInfo\n analysisData?: AudioAnalysis\n maxDurationMs?: number\n maxDurationReached?: boolean\n lastRecordingReason?: RecordingStopReason\n}\n\ntype RecorderAction =\n | { type: 'START' | 'PAUSE' | 'RESUME' }\n | {\n type: 'STOP'\n payload: {\n reason: RecordingStopReason\n }\n }\n | {\n type: 'UPDATE_RECORDING_STATE'\n payload: {\n isRecording: boolean\n isPaused: boolean\n }\n }\n | {\n type: 'UPDATE_STATUS'\n payload: {\n durationMs: number\n size: number\n compression?: CompressionInfo\n maxDurationMs?: number\n maxDurationReached?: boolean\n }\n }\n | {\n type: 'MAX_DURATION_REACHED'\n payload: MaxDurationReachedEvent\n }\n | { type: 'UPDATE_ANALYSIS'; payload: AudioAnalysis }\n\nconst defaultAnalysis: AudioAnalysis = {\n segmentDurationMs: 100,\n bitDepth: 32,\n numberOfChannels: 1,\n durationMs: 0,\n sampleRate: 44100,\n samples: 0,\n dataPoints: [],\n rmsRange: {\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n },\n amplitudeRange: {\n min: Number.POSITIVE_INFINITY,\n max: Number.NEGATIVE_INFINITY,\n },\n extractionTimeMs: 0,\n}\n\nfunction finiteOrZero(value: number): number {\n return Number.isFinite(value) ? value : 0\n}\n\nfunction sanitizeSerializableValue<T>(value: T): T {\n if (typeof value === 'number') {\n return finiteOrZero(value) as T\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeSerializableValue(item)) as T\n }\n\n if (value && typeof value === 'object') {\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, nestedValue] of Object.entries(\n value as Record<string, unknown>\n )) {\n sanitized[key] = sanitizeSerializableValue(nestedValue)\n }\n\n return sanitized as T\n }\n\n return value\n}\n\nfunction createSerializableAnalysis(analysis: AudioAnalysis): AudioAnalysis {\n return sanitizeSerializableValue(analysis)\n}\n\nfunction createRecordingSnapshot(recording: AudioRecording): AudioRecording {\n return sanitizeSerializableValue(recording)\n}\n\nfunction audioRecorderReducer(\n state: RecorderReducerState,\n action: RecorderAction\n): RecorderReducerState {\n switch (action.type) {\n case 'START':\n return {\n ...state,\n isRecording: true,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n analysisData: defaultAnalysis,\n maxDurationMs: undefined,\n maxDurationReached: false,\n lastRecordingReason: undefined,\n }\n case 'STOP':\n return {\n ...state,\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n analysisData: undefined,\n lastRecordingReason: action.payload.reason,\n // Preserve max-duration state after stop so UI and agentic\n // validation can explain why recording ended. START resets it.\n }\n case 'PAUSE':\n return { ...state, isPaused: true, isRecording: false }\n case 'RESUME':\n return { ...state, isPaused: false, isRecording: true }\n case 'UPDATE_RECORDING_STATE':\n return {\n ...state,\n isPaused: action.payload.isPaused,\n isRecording: action.payload.isRecording,\n }\n case 'UPDATE_STATUS': {\n const newState = {\n ...state,\n durationMs: action.payload.durationMs,\n size: action.payload.size,\n compression: action.payload.compression\n ? {\n size: action.payload.compression.size,\n mimeType: action.payload.compression.mimeType,\n bitrate: action.payload.compression.bitrate,\n format: action.payload.compression.format,\n }\n : undefined,\n maxDurationMs: action.payload.maxDurationMs,\n maxDurationReached: action.payload.maxDurationReached,\n }\n return newState\n }\n case 'MAX_DURATION_REACHED':\n return {\n ...state,\n maxDurationMs: action.payload.maxDurationMs,\n maxDurationReached: true,\n }\n case 'UPDATE_ANALYSIS':\n return {\n ...state,\n analysisData: action.payload,\n }\n default:\n return state\n }\n}\n\ninterface HandleAudioAnalysisProps {\n analysis: AudioAnalysis\n visualizationDuration: number\n}\n\nfunction shouldKeepFullAnalysis(config?: RecordingConfig | null): boolean {\n return config?.keepFullAnalysis !== false\n}\n\nexport function useAudioRecorder({\n logger,\n audioWorkletUrl,\n featuresExtratorUrl,\n}: UseAudioRecorderProps = {}): UseAudioRecorderState {\n // Initialize AudioDeviceManager with logger (once)\n if (logger) {\n audioDeviceManager.setLogger(logger)\n }\n const [state, dispatch] = useReducer(audioRecorderReducer, {\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n analysisData: undefined,\n maxDurationMs: undefined,\n maxDurationReached: false,\n lastRecordingReason: undefined,\n })\n\n const startResultRef = useRef<StartRecordingResult | null>(null)\n\n const analysisListenerRef = useRef<EventSubscription | null>(null)\n // analysisRef is the current analysis data (last 10 seconds by default)\n const analysisRef = useRef<AudioAnalysis>({ ...defaultAnalysis })\n // fullAnalysisRef is the full analysis data (all data points)\n const fullAnalysisRef = useRef<AudioAnalysis>({\n ...defaultAnalysis,\n })\n\n // Instantiate the module for web with URLs\n const audioStudio =\n Platform.OS === 'web'\n ? AudioStudioModule({\n audioWorkletUrl,\n featuresExtratorUrl,\n logger,\n })\n : AudioStudioModule\n\n const onAudioStreamRef = useRef<\n ((_: AudioDataEvent) => Promise<void>) | null\n >(null)\n\n const stateRef = useRef({\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined as CompressionInfo | undefined,\n maxDurationMs: undefined as number | undefined,\n maxDurationReached: false,\n })\n\n const recordingConfigRef = useRef<RecordingConfig | null>(null)\n const maxDurationHandledRef = useRef(false)\n const stopFinalizationRef = useRef<Promise<AudioRecording> | null>(null)\n\n // Generate unique instance ID for debugging\n const instanceId = useId().replace(/:/g, '').slice(0, 5)\n\n const handleAudioAnalysis = useCallback(\n async ({\n analysis,\n visualizationDuration,\n }: HandleAudioAnalysisProps) => {\n const savedAnalysisData = analysisRef.current || {\n ...defaultAnalysis,\n }\n\n const maxDuration = visualizationDuration\n\n logger?.debug(\n `[handleAudioAnalysis] Received audio analysis: maxDuration=${maxDuration} analysis.dataPoints=${analysis.dataPoints.length} analysisData.dataPoints=${savedAnalysisData.dataPoints.length}`\n )\n\n // Combine data points\n const combinedDataPoints = [\n ...savedAnalysisData.dataPoints,\n ...analysis.dataPoints,\n ]\n\n const keepFullAnalysis = shouldKeepFullAnalysis(\n recordingConfigRef.current\n )\n const fullCombinedDataPoints = keepFullAnalysis\n ? [\n ...(fullAnalysisRef.current?.dataPoints ?? []),\n ...analysis.dataPoints,\n ]\n : undefined\n\n // Calculate the new duration\n // The number of segments is based on how many segments of segmentDurationMs can fit in visualizationDuration\n const numberOfSegments = Math.ceil(\n visualizationDuration / analysis.segmentDurationMs\n )\n // maxDataPoints should be the number of data points, not milliseconds\n const maxDataPoints = numberOfSegments\n\n logger?.debug(\n `[handleAudioAnalysis] Combined data points before trimming: numberOfSegments=${numberOfSegments} visualizationDuration=${visualizationDuration} combinedDataPointsLength=${combinedDataPoints.length} vs maxDataPoints=${maxDataPoints}`\n )\n\n // Trim data points to keep within the maximum number of data points\n if (combinedDataPoints.length > maxDataPoints) {\n combinedDataPoints.splice(\n 0,\n combinedDataPoints.length - maxDataPoints\n )\n }\n\n // Keep the full data points when requested for stopRecording().analysisData.\n if (keepFullAnalysis && fullCombinedDataPoints) {\n fullAnalysisRef.current = {\n ...fullAnalysisRef.current,\n dataPoints: fullCombinedDataPoints,\n }\n fullAnalysisRef.current.durationMs =\n fullCombinedDataPoints.length * analysis.segmentDurationMs\n }\n savedAnalysisData.dataPoints = combinedDataPoints\n savedAnalysisData.bitDepth =\n analysis.bitDepth || savedAnalysisData.bitDepth\n savedAnalysisData.durationMs =\n combinedDataPoints.length * analysis.segmentDurationMs\n\n // Update amplitude range\n const newMin = Math.min(\n savedAnalysisData.amplitudeRange.min,\n analysis.amplitudeRange.min\n )\n const newMax = Math.max(\n savedAnalysisData.amplitudeRange.max,\n analysis.amplitudeRange.max\n )\n\n savedAnalysisData.amplitudeRange = {\n min: newMin,\n max: newMax,\n }\n if (keepFullAnalysis) {\n fullAnalysisRef.current.amplitudeRange = {\n min: newMin,\n max: newMax,\n }\n }\n\n logger?.debug(\n `[handleAudioAnalysis] Updated analysis data: durationMs=${savedAnalysisData.durationMs}`,\n { dataPoints: savedAnalysisData.dataPoints.length }\n )\n\n // Call the onAudioAnalysis callback if it exists in the recording config\n if (recordingConfigRef.current?.onAudioAnalysis) {\n recordingConfigRef.current\n .onAudioAnalysis(analysis)\n .catch((error) => {\n logger?.warn(`Error processing audio analysis:`, error)\n })\n }\n\n // Update the ref\n analysisRef.current = savedAnalysisData\n\n // Dispatch the updated analysis data to state to trigger re-render\n dispatch({\n type: 'UPDATE_ANALYSIS',\n payload: { ...savedAnalysisData },\n })\n },\n [dispatch]\n )\n\n const handleAudioEvent = useCallback(\n async (eventData: AudioEventPayload) => {\n const {\n fileUri,\n deltaSize,\n totalSize,\n lastEmittedSize,\n position,\n streamUuid,\n encoded,\n pcmFloat32,\n mimeType,\n buffer,\n compression,\n } = eventData\n logger?.debug(`[handleAudioEvent] Received audio event:`, {\n fileUri,\n deltaSize,\n totalSize,\n position,\n mimeType,\n lastEmittedSize,\n streamUuid,\n encodedLength: encoded?.length,\n compression,\n })\n if (deltaSize === 0) {\n // Ignore packet with no data\n return\n }\n try {\n // Coming from native ( ios / android ) otherwise buffer is set\n if (Platform.OS !== 'web') {\n const compressionPayload =\n compression && startResultRef.current?.compression\n ? {\n data: compression.data,\n size: compression.totalSize,\n mimeType:\n startResultRef.current.compression\n ?.mimeType,\n bitrate:\n startResultRef.current.compression\n ?.bitrate,\n format: startResultRef.current.compression\n ?.format,\n }\n : undefined\n if (pcmFloat32 != null) {\n // Android new arch delivers Float32Array; iOS delivers number[] — normalize both\n const float32 =\n pcmFloat32 instanceof Float32Array\n ? pcmFloat32\n : new Float32Array(pcmFloat32 as number[])\n onAudioStreamRef.current?.({\n data: float32,\n streamFormat: 'float32',\n position,\n fileUri,\n eventDataSize: deltaSize,\n totalSize,\n compression: compressionPayload,\n })\n } else {\n if (!encoded) {\n logger?.error(`Encoded audio data is missing`)\n throw new Error('Encoded audio data is missing')\n }\n onAudioStreamRef.current?.({\n data: encoded,\n position,\n fileUri,\n eventDataSize: deltaSize,\n totalSize,\n compression: compressionPayload,\n })\n }\n } else if (buffer) {\n // Coming from web\n const webEvent: AudioDataEvent = {\n data: buffer,\n position,\n fileUri,\n eventDataSize: deltaSize,\n totalSize,\n compression:\n compression && startResultRef.current?.compression\n ? {\n data: compression.data,\n size: compression.totalSize,\n mimeType:\n startResultRef.current.compression\n ?.mimeType,\n bitrate:\n startResultRef.current.compression\n ?.bitrate,\n format: startResultRef.current.compression\n ?.format,\n }\n : undefined,\n }\n onAudioStreamRef.current?.(webEvent)\n logger?.debug(\n `[handleAudioEvent] Audio data sent to onAudioStream`,\n webEvent\n )\n }\n } catch (error) {\n logger?.error(`Error processing audio event:`, error)\n }\n },\n []\n )\n\n const finalizeRecordingStop = useCallback(\n async (reason: RecordingStopReason) => {\n if (stopFinalizationRef.current) {\n return stopFinalizationRef.current\n }\n\n const finalizePromise = (async () => {\n const nativeStopResult: AudioRecording | null =\n await audioStudio.stopRecording()\n\n if (!nativeStopResult) {\n throw new Error('Failed to stop recording')\n }\n\n const stopResult = createRecordingSnapshot(nativeStopResult)\n\n if (shouldKeepFullAnalysis(recordingConfigRef.current)) {\n stopResult.analysisData = createSerializableAnalysis(\n fullAnalysisRef.current\n )\n } else {\n // `keepFullAnalysis` is a hook-level retention policy. If a platform\n // starts returning native analysisData in the future, keep opt-out\n // semantics explicit and avoid leaking a full history here.\n delete stopResult.analysisData\n }\n\n if (analysisListenerRef.current) {\n analysisListenerRef.current.remove()\n analysisListenerRef.current = null\n }\n onAudioStreamRef.current = null\n\n stateRef.current.isRecording = false\n stateRef.current.isPaused = false\n\n // Note: We deliberately DON'T clear recordingConfigRef here to preserve callbacks.\n logger?.debug(`recording stopped`, stopResult)\n maxDurationHandledRef.current = false\n dispatch({\n type: 'STOP',\n payload: { reason },\n })\n\n const stoppedCallback =\n recordingConfigRef.current?.onRecordingStopped\n if (stoppedCallback) {\n try {\n void Promise.resolve(\n stoppedCallback(stopResult, reason)\n ).catch((error) => {\n logger?.error(\n `Error in recording stopped callback:`,\n error\n )\n })\n } catch (error) {\n logger?.error(\n `Error in recording stopped callback:`,\n error\n )\n }\n }\n\n return stopResult\n })()\n\n stopFinalizationRef.current = finalizePromise\n try {\n return await finalizePromise\n } finally {\n stopFinalizationRef.current = null\n }\n },\n [audioStudio, dispatch, logger]\n )\n\n const handleMaxDurationReached = useCallback(\n async (event: MaxDurationReachedEvent) => {\n if (maxDurationHandledRef.current) {\n return\n }\n\n maxDurationHandledRef.current = true\n const config = recordingConfigRef.current\n const callbackEvent: MaxDurationReachedEvent = {\n ...event,\n autoStopped:\n event.autoStopped || !!config?.autoStopOnMaxDuration,\n }\n\n stateRef.current.maxDurationMs = callbackEvent.maxDurationMs\n stateRef.current.maxDurationReached = true\n dispatch({\n type: 'MAX_DURATION_REACHED',\n payload: callbackEvent,\n })\n\n try {\n config?.onMaxDurationReached?.(callbackEvent)\n } catch (error) {\n logger?.error(`Error in max duration callback:`, error)\n }\n\n if (config?.autoStopOnMaxDuration && stateRef.current.isRecording) {\n try {\n await finalizeRecordingStop('maxDuration')\n } catch (error) {\n logger?.error(`Error auto-stopping on max duration:`, error)\n }\n }\n },\n [dispatch, finalizeRecordingStop, logger]\n )\n\n const checkStatus = useCallback(async () => {\n try {\n const status: AudioStreamStatus = audioStudio.status()\n logger?.debug(\n `Status: paused: ${status.isPaused} isRecording: ${status.isRecording} durationMs: ${status.durationMs} size: ${status.size}`,\n status.compression\n )\n\n if (\n status.maxDurationReached === true &&\n status.maxDurationMs != null &&\n !stateRef.current.maxDurationReached\n ) {\n await handleMaxDurationReached({\n durationMs: status.durationMs,\n maxDurationMs: status.maxDurationMs,\n overrunMs: Math.max(\n 0,\n status.durationMs - status.maxDurationMs\n ),\n autoStopped: false,\n })\n }\n\n // Only dispatch if values actually changed\n if (\n status.isRecording !== stateRef.current.isRecording ||\n status.isPaused !== stateRef.current.isPaused\n ) {\n stateRef.current.isRecording = status.isRecording\n stateRef.current.isPaused = status.isPaused\n dispatch({\n type: 'UPDATE_RECORDING_STATE',\n payload: {\n isRecording: status.isRecording,\n isPaused: status.isPaused,\n },\n })\n }\n\n const statusMaxDurationReached = status.maxDurationReached ?? false\n const preserveStoppedMaxDuration =\n !status.isRecording &&\n !status.isPaused &&\n stateRef.current.maxDurationReached &&\n !statusMaxDurationReached\n const nextMaxDurationMs = preserveStoppedMaxDuration\n ? stateRef.current.maxDurationMs\n : status.maxDurationMs\n const nextMaxDurationReached = preserveStoppedMaxDuration\n ? true\n : statusMaxDurationReached\n\n if (\n status.durationMs !== stateRef.current.durationMs ||\n status.size !== stateRef.current.size ||\n nextMaxDurationMs !== stateRef.current.maxDurationMs ||\n nextMaxDurationReached !== stateRef.current.maxDurationReached\n ) {\n stateRef.current.durationMs = status.durationMs\n stateRef.current.size = status.size\n stateRef.current.compression = status.compression\n stateRef.current.maxDurationMs = nextMaxDurationMs\n stateRef.current.maxDurationReached = nextMaxDurationReached\n dispatch({\n type: 'UPDATE_STATUS',\n payload: {\n durationMs: status.durationMs,\n size: status.size,\n compression: status.compression,\n maxDurationMs: nextMaxDurationMs,\n maxDurationReached: nextMaxDurationReached,\n },\n })\n }\n } catch (error) {\n logger?.error(`Error getting status:`, error)\n }\n }, [audioStudio, handleMaxDurationReached, logger])\n\n // Update ref when state changes\n useEffect(() => {\n stateRef.current = {\n isRecording: state.isRecording,\n isPaused: state.isPaused,\n durationMs: state.durationMs,\n size: state.size,\n compression: state.compression,\n maxDurationMs: state.maxDurationMs,\n maxDurationReached: state.maxDurationReached ?? false,\n }\n }, [\n state.isRecording,\n state.isPaused,\n state.durationMs,\n state.size,\n state.compression,\n state.maxDurationMs,\n state.maxDurationReached,\n ])\n\n const startRecording = useCallback(\n async (recordingOptions: RecordingConfig) => {\n // Validate the encoding configuration\n const validationResult = validateRecordingConfig({\n encoding: recordingOptions.encoding,\n })\n\n // Log warnings if any\n if (validationResult.warnings.length > 0) {\n validationResult.warnings.forEach((warning) => {\n logger?.warn(warning)\n })\n }\n\n // Update recording options with validated values\n const validatedOptions = {\n ...recordingOptions,\n encoding: validationResult.encoding,\n }\n\n recordingConfigRef.current = validatedOptions\n maxDurationHandledRef.current = false\n logger?.debug(\n `start recording with validated config`,\n validatedOptions\n )\n\n analysisRef.current = { ...defaultAnalysis } // Reset analysis data\n fullAnalysisRef.current = { ...defaultAnalysis }\n const { onAudioStream, enableProcessing } = validatedOptions\n\n const maxRecentDataDuration = 10000 // TODO compute maxRecentDataDuration based on screen dimensions\n if (typeof onAudioStream === 'function') {\n onAudioStreamRef.current = onAudioStream\n } else {\n logger?.warn(`onAudioStream is not a function`, onAudioStream)\n onAudioStreamRef.current = null\n }\n // Strip hook-only values and undefineds that can't cross the native bridge.\n // autoStopOnMaxDuration stays hook-owned so finalization can expose\n // the same AudioRecording result as a manual stop.\n const cleanOptions = createNativeRecordingOptions(validatedOptions)\n const startResult: StartRecordingResult =\n await audioStudio.startRecording(cleanOptions)\n dispatch({ type: 'START' })\n\n startResultRef.current = startResult\n\n if (enableProcessing) {\n logger?.debug(`Enabling audio analysis listener`)\n const listener = addAudioAnalysisListener(\n async (analysisData) => {\n try {\n await handleAudioAnalysis({\n analysis: analysisData,\n visualizationDuration: maxRecentDataDuration,\n })\n } catch (error) {\n logger?.warn(\n `Error processing audio analysis:`,\n error\n )\n }\n }\n )\n\n analysisListenerRef.current = listener\n }\n\n return startResult\n },\n [handleAudioAnalysis, dispatch]\n )\n\n const prepareRecording = useCallback(\n async (recordingOptions: RecordingConfig) => {\n recordingConfigRef.current = recordingOptions\n logger?.debug(`preparing recording`, recordingOptions)\n\n analysisRef.current = { ...defaultAnalysis } // Reset analysis data\n fullAnalysisRef.current = { ...defaultAnalysis }\n const { onAudioStream } = recordingOptions\n\n // Store onAudioStream for later use when recording starts\n if (typeof onAudioStream === 'function') {\n onAudioStreamRef.current = onAudioStream\n } else {\n logger?.warn(`onAudioStream is not a function`, onAudioStream)\n onAudioStreamRef.current = null\n }\n\n // Strip hook-only values and undefineds that can't cross the native bridge.\n const cleanOptions = createNativeRecordingOptions(recordingOptions)\n // Call the native prepareRecording method\n await audioStudio.prepareRecording(cleanOptions)\n logger?.debug(`recording prepared successfully`)\n },\n []\n )\n\n const stopRecording = useCallback(async () => {\n logger?.debug(`stoping recording`)\n return finalizeRecordingStop('manual')\n }, [finalizeRecordingStop, logger])\n\n const pauseRecording = useCallback(async () => {\n logger?.debug(`pause recording`)\n const pauseResult = await audioStudio.pauseRecording()\n dispatch({ type: 'PAUSE' })\n return pauseResult\n }, [dispatch])\n\n const resumeRecording = useCallback(async () => {\n logger?.debug(`resume recording`)\n const resumeResult = await audioStudio.resumeRecording()\n dispatch({ type: 'RESUME' })\n return resumeResult\n }, [dispatch])\n\n useEffect(() => {\n const subscription = addMaxDurationReachedListener(async (event) => {\n await handleMaxDurationReached(event)\n })\n\n return () => {\n subscription.remove()\n }\n }, [handleMaxDurationReached])\n\n useEffect(() => {\n let intervalId: ReturnType<typeof setInterval> | undefined\n\n if (state.isRecording || state.isPaused) {\n // Immediately check status when starting\n checkStatus()\n\n // Start interval\n intervalId = setInterval(checkStatus, 1000)\n }\n\n return () => {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = undefined\n }\n }\n }, [checkStatus, state.isRecording, state.isPaused])\n\n useEffect(() => {\n logger?.debug(`Registering audio event listener`)\n const subscribeAudio = addAudioEventListener(handleAudioEvent)\n\n logger?.debug(\n `Subscribed to audio event listener and analysis listener`,\n {\n subscribeAudio,\n }\n )\n\n return () => {\n logger?.debug(`Removing audio event listener`)\n subscribeAudio.remove()\n }\n }, [handleAudioEvent, handleAudioAnalysis])\n\n useEffect(() => {\n // Add event subscription for recording interruptions\n logger?.debug(\n `Setting up recording interruption listener [${instanceId}]`\n )\n\n const subscription = addRecordingInterruptionListener((event) => {\n logger?.debug(\n `[${instanceId}] Received recording interruption event:`,\n event\n )\n\n // Handle device disconnection for UI updates\n if (event.reason === 'deviceDisconnected') {\n logger?.debug(\n `[${instanceId}] Device disconnected - temporarily hiding last device from UI`\n )\n\n // Get current device list before the native layer updates\n const currentDevices = audioDeviceManager.getRawDevices()\n\n // Wait a moment for native layer to update, then compare\n setTimeout(async () => {\n try {\n // Get updated devices without notifying yet\n const updatedDevices =\n await audioDeviceManager.getAvailableDevices({\n refresh: true,\n })\n\n // Find missing devices by comparing lists\n const missingDevices = currentDevices.filter(\n (oldDevice) =>\n !updatedDevices.some(\n (newDevice) => newDevice.id === oldDevice.id\n )\n )\n\n if (missingDevices.length > 0) {\n // Mark all missing devices as disconnected (silently)\n missingDevices.forEach((missingDevice) => {\n logger?.debug(\n `[${instanceId}] Confirmed disconnected device: ${missingDevice.name} (${missingDevice.id})`\n )\n audioDeviceManager.markDeviceAsDisconnected(\n missingDevice.id,\n false\n )\n })\n }\n\n // Notify listeners once with the final filtered state\n audioDeviceManager.notifyListeners()\n } catch (error) {\n logger?.warn(\n `[${instanceId}] Error in delayed device disconnection handling:`,\n error\n )\n }\n }, 500) // 500ms delay to let native layer update\n } else if (event.reason === 'deviceConnected') {\n // Device reconnected - force refresh to show it immediately\n logger?.debug(\n `[${instanceId}] Device connected, forcing refresh`\n )\n audioDeviceManager.forceRefreshDevices()\n }\n\n // Check if we have a callback configured\n logger?.debug(\n `[${instanceId}] recordingConfigRef.current exists:`,\n !!recordingConfigRef.current\n )\n\n if (recordingConfigRef.current?.onRecordingInterrupted) {\n try {\n logger?.debug(\n `[${instanceId}] Calling recording interruption callback`\n )\n recordingConfigRef.current.onRecordingInterrupted(event)\n } catch (error) {\n logger?.error(\n `[${instanceId}] Error in recording interruption callback:`,\n error\n )\n }\n } else {\n logger?.debug(\n `[${instanceId}] No recording interruption callback configured`\n )\n }\n })\n\n return () => {\n logger?.debug(\n `[${instanceId}] Removing recording interruption listener`\n )\n subscription.remove()\n }\n }, [instanceId, logger]) // Include instanceId and logger in dependencies\n\n return {\n prepareRecording,\n startRecording,\n stopRecording,\n pauseRecording,\n resumeRecording,\n isPaused: state.isPaused,\n isRecording: state.isRecording,\n durationMs: state.durationMs,\n size: state.size,\n compression: state.compression,\n analysisData: state.analysisData,\n maxDurationMs: state.maxDurationMs,\n maxDurationReached: state.maxDurationReached,\n lastRecordingReason: state.lastRecordingReason,\n }\n}\n"]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createNativeRecordingOptions = createNativeRecordingOptions;
|
|
4
|
+
const cleanNativeOptions_1 = require("./cleanNativeOptions");
|
|
5
|
+
function createNativeRecordingOptions(recordingOptions) {
|
|
6
|
+
const { onAudioStream, onRecordingInterrupted, onMaxDurationReached, onRecordingStopped, onAudioAnalysis, keepFullAnalysis: _keepFullAnalysis,
|
|
7
|
+
// Keep hook-owned auto-stop out of the native bridge so the hook can
|
|
8
|
+
// reuse the same finalization path as manual stop and expose the
|
|
9
|
+
// resulting AudioRecording consistently.
|
|
10
|
+
autoStopOnMaxDuration: _autoStopOnMaxDuration, ...options } = recordingOptions;
|
|
11
|
+
return (0, cleanNativeOptions_1.cleanNativeOptions)(options);
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=nativeRecordingOptions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nativeRecordingOptions.js","sourceRoot":"","sources":["../../../src/utils/nativeRecordingOptions.ts"],"names":[],"mappings":";;AAGA,oEAgBC;AAlBD,6DAAyD;AAEzD,SAAgB,4BAA4B,CAAC,gBAAiC;IAC1E,MAAM,EACF,aAAa,EACb,sBAAsB,EACtB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,gBAAgB,EAAE,iBAAiB;IACnC,qEAAqE;IACrE,iEAAiE;IACjE,yCAAyC;IACzC,qBAAqB,EAAE,sBAAsB,EAC7C,GAAG,OAAO,EACb,GAAG,gBAAgB,CAAA;IAEpB,OAAO,IAAA,uCAAkB,EAAC,OAAO,CAAC,CAAA;AACtC,CAAC","sourcesContent":["import { RecordingConfig } from '../AudioStudio.types'\nimport { cleanNativeOptions } from './cleanNativeOptions'\n\nexport function createNativeRecordingOptions(recordingOptions: RecordingConfig) {\n const {\n onAudioStream,\n onRecordingInterrupted,\n onMaxDurationReached,\n onRecordingStopped,\n onAudioAnalysis,\n keepFullAnalysis: _keepFullAnalysis,\n // Keep hook-owned auto-stop out of the native bridge so the hook can\n // reuse the same finalization path as manual stop and expose the\n // resulting AudioRecording consistently.\n autoStopOnMaxDuration: _autoStopOnMaxDuration,\n ...options\n } = recordingOptions\n\n return cleanNativeOptions(options)\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const nativeRecordingOptions_1 = require("./nativeRecordingOptions");
|
|
4
|
+
describe('createNativeRecordingOptions', () => {
|
|
5
|
+
it('keeps maxDurationMs native but leaves auto-stop finalization hook-owned', () => {
|
|
6
|
+
const nativeOptions = (0, nativeRecordingOptions_1.createNativeRecordingOptions)({
|
|
7
|
+
maxDurationMs: 1500,
|
|
8
|
+
autoStopOnMaxDuration: true,
|
|
9
|
+
onMaxDurationReached: jest.fn(),
|
|
10
|
+
onRecordingStopped: jest.fn(),
|
|
11
|
+
onRecordingInterrupted: jest.fn(),
|
|
12
|
+
onAudioAnalysis: jest.fn(),
|
|
13
|
+
onAudioStream: jest.fn(),
|
|
14
|
+
keepFullAnalysis: true,
|
|
15
|
+
sampleRate: 16000,
|
|
16
|
+
});
|
|
17
|
+
expect(nativeOptions).toMatchObject({
|
|
18
|
+
maxDurationMs: 1500,
|
|
19
|
+
sampleRate: 16000,
|
|
20
|
+
});
|
|
21
|
+
expect(nativeOptions).not.toHaveProperty('autoStopOnMaxDuration');
|
|
22
|
+
expect(nativeOptions).not.toHaveProperty('onMaxDurationReached');
|
|
23
|
+
expect(nativeOptions).not.toHaveProperty('onRecordingStopped');
|
|
24
|
+
expect(nativeOptions).not.toHaveProperty('onRecordingInterrupted');
|
|
25
|
+
expect(nativeOptions).not.toHaveProperty('onAudioAnalysis');
|
|
26
|
+
expect(nativeOptions).not.toHaveProperty('onAudioStream');
|
|
27
|
+
expect(nativeOptions).not.toHaveProperty('keepFullAnalysis');
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
//# sourceMappingURL=nativeRecordingOptions.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nativeRecordingOptions.test.js","sourceRoot":"","sources":["../../../src/utils/nativeRecordingOptions.test.ts"],"names":[],"mappings":";;AAAA,qEAAuE;AAEvE,QAAQ,CAAC,8BAA8B,EAAE,GAAG,EAAE;IAC1C,EAAE,CAAC,yEAAyE,EAAE,GAAG,EAAE;QAC/E,MAAM,aAAa,GAAG,IAAA,qDAA4B,EAAC;YAC/C,aAAa,EAAE,IAAI;YACnB,qBAAqB,EAAE,IAAI;YAC3B,oBAAoB,EAAE,IAAI,CAAC,EAAE,EAAE;YAC/B,kBAAkB,EAAE,IAAI,CAAC,EAAE,EAAE;YAC7B,sBAAsB,EAAE,IAAI,CAAC,EAAE,EAAE;YACjC,eAAe,EAAE,IAAI,CAAC,EAAE,EAAE;YAC1B,aAAa,EAAE,IAAI,CAAC,EAAE,EAAE;YACxB,gBAAgB,EAAE,IAAI;YACtB,UAAU,EAAE,KAAK;SACpB,CAAC,CAAA;QAEF,MAAM,CAAC,aAAa,CAAC,CAAC,aAAa,CAAC;YAChC,aAAa,EAAE,IAAI;YACnB,UAAU,EAAE,KAAK;SACpB,CAAC,CAAA;QACF,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,uBAAuB,CAAC,CAAA;QACjE,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAA;QAChE,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAA;QAC9D,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,wBAAwB,CAAC,CAAA;QAClE,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,iBAAiB,CAAC,CAAA;QAC3D,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,eAAe,CAAC,CAAA;QACzD,MAAM,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,kBAAkB,CAAC,CAAA;IAChE,CAAC,CAAC,CAAA;AACN,CAAC,CAAC,CAAA","sourcesContent":["import { createNativeRecordingOptions } from './nativeRecordingOptions'\n\ndescribe('createNativeRecordingOptions', () => {\n it('keeps maxDurationMs native but leaves auto-stop finalization hook-owned', () => {\n const nativeOptions = createNativeRecordingOptions({\n maxDurationMs: 1500,\n autoStopOnMaxDuration: true,\n onMaxDurationReached: jest.fn(),\n onRecordingStopped: jest.fn(),\n onRecordingInterrupted: jest.fn(),\n onAudioAnalysis: jest.fn(),\n onAudioStream: jest.fn(),\n keepFullAnalysis: true,\n sampleRate: 16000,\n })\n\n expect(nativeOptions).toMatchObject({\n maxDurationMs: 1500,\n sampleRate: 16000,\n })\n expect(nativeOptions).not.toHaveProperty('autoStopOnMaxDuration')\n expect(nativeOptions).not.toHaveProperty('onMaxDurationReached')\n expect(nativeOptions).not.toHaveProperty('onRecordingStopped')\n expect(nativeOptions).not.toHaveProperty('onRecordingInterrupted')\n expect(nativeOptions).not.toHaveProperty('onAudioAnalysis')\n expect(nativeOptions).not.toHaveProperty('onAudioStream')\n expect(nativeOptions).not.toHaveProperty('keepFullAnalysis')\n })\n})\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AudioStudio.types.js","sourceRoot":"","sources":["../../src/AudioStudio.types.ts"],"names":[],"mappings":"AA+VA,4EAA4E;AAC5E,MAAM,CAAC,MAAM,2BAA2B,GAAG;IACvC,8CAA8C;IAC9C,KAAK,EAAE,OAAO;IACd,sDAAsD;IACtD,QAAQ,EAAE,UAAU;CACd,CAAA","sourcesContent":["// packages/audio-studio/src/AudioStudio.types.ts\nimport {\n AudioAnalysis,\n AudioFeaturesOptions,\n DecodingConfig,\n} from './AudioAnalysis/AudioAnalysis.types'\nimport type { AudioAnalysisEvent } from './events'\n\nexport interface CompressionInfo {\n /** Size of the compressed audio data in bytes */\n size: number\n /** MIME type of the compressed audio (e.g., 'audio/aac', 'audio/opus') */\n mimeType: string\n /** Bitrate of the compressed audio in bits per second */\n bitrate: number\n /** Format of the compression (e.g., 'aac', 'opus') */\n format: string\n /** URI to the compressed audio file if available */\n compressedFileUri?: string\n}\n\nexport interface AudioStreamStatus {\n /** Indicates whether audio recording is currently active */\n isRecording: boolean\n /** Indicates whether recording is in a paused state */\n isPaused: boolean\n /** Duration of the current recording in milliseconds */\n durationMs: number\n /** Size of the recorded audio data in bytes */\n size: number\n /** Interval in milliseconds at which recording data is emitted */\n interval: number\n /** Interval in milliseconds at which analysis data is emitted */\n intervalAnalysis: number\n /** MIME type of the recorded audio (e.g., 'audio/wav') */\n mimeType: string\n /** Information about audio compression if enabled */\n compression?: CompressionInfo\n /** Configured maximum active recording duration in milliseconds, if enabled */\n maxDurationMs?: number\n /** Whether the current recording session has reached the configured maximum duration */\n maxDurationReached?: boolean\n}\n\ninterface AudioDataEventBase {\n /** Current position in the audio stream in bytes */\n position: number\n /** URI to the file being recorded */\n fileUri: string\n /** Size of the current data chunk in bytes */\n eventDataSize: number\n /** Total size of the recording so far in bytes */\n totalSize: number\n /** Information about compression if enabled, including the compressed data chunk */\n compression?: CompressionInfo & {\n /** Base64 (native) or Blob (web) encoded compressed data chunk */\n data?: string | Blob\n }\n}\n\nexport interface AudioDataEventRaw extends AudioDataEventBase {\n /** Audio data as base64 string (native), Float32Array (web), or Int16Array (web) */\n data: string | Float32Array | Int16Array\n streamFormat?: undefined | 'raw'\n}\n\nexport interface AudioDataEventFloat32 extends AudioDataEventBase {\n /** Audio data as Float32Array with samples in [-1, 1] range */\n data: Float32Array\n streamFormat: 'float32'\n}\n\nexport type AudioDataEvent = AudioDataEventRaw | AudioDataEventFloat32\n\n/**\n * Audio encoding types supported by the library.\n *\n * Platform support:\n * - `pcm_8bit`: Android only (iOS/Web will fallback to 16-bit)\n * - `pcm_16bit`: All platforms\n * - `pcm_32bit`: All platforms\n *\n * @see {@link https://github.com/deeeed/audiolab/blob/main/packages/audio-studio/docs/PLATFORM_LIMITATIONS.md | Platform Limitations}\n */\nexport type EncodingType = 'pcm_32bit' | 'pcm_16bit' | 'pcm_8bit'\n\n/**\n * Supported audio sample rates in Hz.\n * All platforms support these standard rates.\n */\nexport type SampleRate = 16000 | 44100 | 48000\n\n/**\n * Audio bit depth (bits per sample).\n *\n * Platform support:\n * - `8`: Android only (iOS/Web will fallback to 16)\n * - `16`: All platforms (recommended for compatibility)\n * - `32`: All platforms\n *\n * @see {@link https://github.com/deeeed/audiolab/blob/main/packages/audio-studio/docs/PLATFORM_LIMITATIONS.md | Platform Limitations}\n */\nexport type BitDepth = 8 | 16 | 32\n\n/**\n * PCM format string representation.\n * @deprecated Use `EncodingType` directly\n */\nexport type PCMFormat = `pcm_${BitDepth}bit`\n\nexport type ConsoleLike = {\n /** Logs a message with optional arguments */\n log: (message: string, ...args: unknown[]) => void\n /** Logs a debug message with optional arguments */\n debug: (message: string, ...args: unknown[]) => void\n /** Logs an info message with optional arguments */\n info: (message: string, ...args: unknown[]) => void\n /** Logs a warning message with optional arguments */\n warn: (message: string, ...args: unknown[]) => void\n /** Logs an error message with optional arguments */\n error: (message: string, ...args: unknown[]) => void\n}\n\nexport interface Chunk {\n /** Transcribed text content */\n text: string\n /** Start and end timestamp in seconds [start, end] where end can be null if ongoing */\n timestamp: [number, number | null]\n}\n\nexport interface TranscriberData {\n /** Unique identifier for the transcription */\n id: string\n /** Indicates if the transcriber is currently processing */\n isBusy: boolean\n /** Complete transcribed text */\n text: string\n /** Start time of the transcription in milliseconds */\n startTime: number\n /** End time of the transcription in milliseconds */\n endTime: number\n /** Array of transcribed text chunks with timestamps */\n chunks: Chunk[]\n}\n\nexport interface AudioRecording {\n /** URI to the recorded audio file */\n fileUri: string\n /** Filename of the recorded audio */\n filename: string\n /** Duration of the recording in milliseconds */\n durationMs: number\n /** Size of the recording in bytes */\n size: number\n /** MIME type of the recorded audio */\n mimeType: string\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels: number\n /** Bit depth of the audio (8, 16, or 32 bits) */\n bitDepth: BitDepth\n /** Sample rate of the audio in Hz */\n sampleRate: SampleRate\n /** Timestamp when the recording was created */\n createdAt?: number\n /** Array of transcription data if available */\n transcripts?: TranscriberData[]\n /**\n * Full analysis data for the recording if processing was enabled and\n * `keepFullAnalysis` was not set to `false`.\n */\n analysisData?: AudioAnalysis\n /** Information about compression if enabled, including the URI to the compressed file */\n compression?: CompressionInfo & {\n /** URI to the compressed audio file */\n compressedFileUri: string\n }\n}\n\nexport interface StartRecordingResult {\n /** URI to the file being recorded */\n fileUri: string\n /** MIME type of the recording */\n mimeType: string\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels?: number\n /** Bit depth of the audio (8, 16, or 32 bits) */\n bitDepth?: BitDepth\n /** Sample rate of the audio in Hz */\n sampleRate?: SampleRate\n /** Information about compression if enabled, including the URI to the compressed file */\n compression?: CompressionInfo & {\n /** URI to the compressed audio file */\n compressedFileUri: string\n }\n}\n\nexport interface MaxDurationReachedEvent {\n /** Active recording duration that triggered the event, in milliseconds */\n durationMs: number\n /** Configured active recording duration limit, in milliseconds */\n maxDurationMs: number\n /** Amount by which timer delivery exceeded the limit, in milliseconds */\n overrunMs: number\n /** Active stream identifier when available */\n streamUuid?: string\n /** Whether the recorder was configured to stop automatically after this event */\n autoStopped: boolean\n}\n\nexport interface AudioSessionConfig {\n /**\n * Audio session category that defines the audio behavior\n * - 'Ambient': Audio continues with silent switch, mixes with other audio\n * - 'SoloAmbient': Audio continues with silent switch, interrupts other audio\n * - 'Playback': Audio continues in background, interrupts other audio\n * - 'Record': Optimized for recording, interrupts other audio\n * - 'PlayAndRecord': Allows simultaneous playback and recording\n * - 'MultiRoute': Routes audio to multiple outputs simultaneously\n */\n category?:\n | 'Ambient'\n | 'SoloAmbient'\n | 'Playback'\n | 'Record'\n | 'PlayAndRecord'\n | 'MultiRoute'\n /**\n * Audio session mode that defines the behavior for specific use cases\n * - 'Default': Standard audio behavior\n * - 'VoiceChat': Optimized for voice chat applications\n * - 'VideoChat': Optimized for video chat applications\n * - 'GameChat': Optimized for in-game chat\n * - 'VideoRecording': Optimized for video recording\n * - 'Measurement': Optimized for audio measurement\n * - 'MoviePlayback': Optimized for movie playback\n * - 'SpokenAudio': Optimized for spoken audio content\n */\n mode?:\n | 'Default'\n | 'VoiceChat'\n | 'VideoChat'\n | 'GameChat'\n | 'VideoRecording'\n | 'Measurement'\n | 'MoviePlayback'\n | 'SpokenAudio'\n /**\n * Options that modify the behavior of the audio session category\n * - 'MixWithOthers': Allows mixing with other active audio sessions\n * - 'DuckOthers': Reduces the volume of other audio sessions\n * - 'InterruptSpokenAudioAndMixWithOthers': Interrupts spoken audio and mixes with others\n * - 'AllowBluetooth': Allows audio routing to Bluetooth devices\n * - 'AllowBluetoothA2DP': Allows audio routing to Bluetooth A2DP devices\n * - 'AllowAirPlay': Allows audio routing to AirPlay devices\n * - 'DefaultToSpeaker': Routes audio to the speaker by default\n */\n categoryOptions?: (\n | 'MixWithOthers'\n | 'DuckOthers'\n | 'InterruptSpokenAudioAndMixWithOthers'\n | 'AllowBluetooth'\n | 'AllowBluetoothA2DP'\n | 'AllowAirPlay'\n | 'DefaultToSpeaker'\n )[]\n}\n\nexport interface IOSConfig {\n /** Configuration for the iOS audio session */\n audioSession?: AudioSessionConfig\n}\n\n/** Android platform specific configuration options */\nexport interface AndroidConfig {\n /**\n * Audio focus strategy for handling interruptions and background behavior\n *\n * - `'background'`: Continue recording when app loses focus (voice recorders, transcription apps)\n * - `'interactive'`: Pause when losing focus, resume when gaining (music apps, games)\n * - `'communication'`: Maintain priority for real-time communication (video calls, voice chat)\n * - `'none'`: No automatic audio focus management (custom handling)\n *\n * @default 'background' when keepAwake=true, 'interactive' otherwise\n */\n audioFocusStrategy?: 'background' | 'interactive' | 'communication' | 'none'\n}\n\n/** Web platform specific configuration options */\nexport interface WebConfig {\n // Reserved for future web-specific options\n}\n\n// Add new type for interruption reasons\nexport type RecordingInterruptionReason =\n /** Audio focus was lost to another app */\n | 'audioFocusLoss'\n /** Audio focus was regained */\n | 'audioFocusGain'\n /** Recording was interrupted by a phone call */\n | 'phoneCall'\n /** Phone call that interrupted recording has ended */\n | 'phoneCallEnded'\n /** Recording was stopped by the system or another app */\n | 'recordingStopped'\n /** Recording device was disconnected */\n | 'deviceDisconnected'\n /** Recording switched to default device after disconnection */\n | 'deviceFallback'\n /** A new audio device was connected */\n | 'deviceConnected'\n /** Device switching failed */\n | 'deviceSwitchFailed'\n\n// Add new interface for interruption events\nexport interface RecordingInterruptionEvent {\n /** The reason for the recording interruption */\n reason: RecordingInterruptionReason\n /** Indicates whether the recording is paused due to the interruption */\n isPaused: boolean\n}\n\nexport interface AudioDeviceCapabilities {\n /** Supported sample rates for the device */\n sampleRates: number[]\n /** Supported channel counts for the device */\n channelCounts: number[]\n /** Supported bit depths for the device */\n bitDepths: number[]\n /** Whether the device supports echo cancellation */\n hasEchoCancellation?: boolean\n /** Whether the device supports noise suppression */\n hasNoiseSuppression?: boolean\n /** Whether the device supports automatic gain control */\n hasAutomaticGainControl?: boolean\n}\n\nexport interface AudioDevice {\n /** Unique identifier for the device */\n id: string\n /** Human-readable name of the device */\n name: string\n /** Device type (builtin_mic, bluetooth, etc.) */\n type: string\n /** Whether this is the system default device */\n isDefault: boolean\n /** Audio capabilities for the device */\n capabilities: AudioDeviceCapabilities\n /** Whether the device is currently available */\n isAvailable: boolean\n}\n\n/** Defines how recording should behave when a device becomes unavailable */\nexport const DeviceDisconnectionBehavior = {\n /** Pause recording when device disconnects */\n PAUSE: 'pause',\n /** Switch to default device and continue recording */\n FALLBACK: 'fallback',\n} as const\n\n/** Type for DeviceDisconnectionBehavior values */\nexport type DeviceDisconnectionBehaviorType =\n (typeof DeviceDisconnectionBehavior)[keyof typeof DeviceDisconnectionBehavior]\n\n/**\n * Configuration for audio output files during recording\n */\nexport interface OutputConfig {\n /**\n * Configuration for the primary (uncompressed) output file\n */\n primary?: {\n /** Whether to create the primary output file (default: true) */\n enabled?: boolean\n /** Format for the primary output (currently only 'wav' is supported) */\n format?: 'wav'\n }\n\n /**\n * Configuration for the compressed output file\n */\n compressed?: {\n /** Whether to create a compressed output file (default: false) */\n enabled?: boolean\n /**\n * Format for compression\n * - 'aac': Advanced Audio Coding - supported on all platforms\n * - 'opus': Opus encoding - supported on Android and Web; on iOS will automatically fall back to AAC\n */\n format?: 'aac' | 'opus'\n /** Bitrate for compression in bits per second (default: 128000) */\n bitrate?: number\n /**\n * Prefer raw stream over container format (Android only)\n * - true: Use raw AAC stream (.aac files) like in v2.10.6\n * - false/undefined: Use M4A container (.m4a files) for better seeking support\n * Note: iOS always produces M4A containers and ignores this flag\n */\n preferRawStream?: boolean\n }\n\n // Future enhancement: Post-processing pipeline\n // postProcessing?: {\n // normalize?: boolean\n // trimSilence?: boolean\n // noiseReduction?: boolean\n // customProcessors?: AudioProcessor[]\n // }\n}\n\nexport interface RecordingConfig {\n /** Sample rate for recording in Hz (16000, 44100, or 48000) */\n sampleRate?: SampleRate\n\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels?: 1 | 2\n\n /**\n * Encoding type for the recording.\n *\n * Platform limitations:\n * - `pcm_8bit`: Android only (iOS/Web will fallback to `pcm_16bit` with warning)\n * - `pcm_16bit`: All platforms (recommended for cross-platform compatibility)\n * - `pcm_32bit`: All platforms\n *\n * The library will automatically validate and adjust the encoding based on\n * platform capabilities. A warning will be logged if fallback is required.\n *\n * @default 'pcm_16bit'\n * @see {@link EncodingType}\n * @see {@link https://github.com/deeeed/audiolab/blob/main/packages/audio-studio/docs/PLATFORM_LIMITATIONS.md | Platform Limitations}\n */\n encoding?: EncodingType\n\n /** Interval in milliseconds at which to emit recording data (minimum: 10ms) */\n interval?: number\n\n /** Interval in milliseconds at which to emit analysis data (minimum: 10ms) */\n intervalAnalysis?: number\n\n /** Keep the device awake while recording (default is false) */\n keepAwake?: boolean\n\n /** Show a notification during recording (default is false) */\n showNotification?: boolean\n\n /** Show waveform in the notification (Android only, when showNotification is true) */\n showWaveformInNotification?: boolean\n\n /** Configuration for the notification */\n notification?: NotificationConfig\n\n /** Enable audio processing (default is false) */\n enableProcessing?: boolean\n\n /**\n * Whether `useAudioRecorder` should retain every audio-analysis data point\n * and attach the full history to `stopRecording().analysisData`.\n *\n * Defaults to `true` for backwards compatibility. Set to `false` for\n * long-running recordings when you only need live `analysisData` state or\n * per-callback `onAudioAnalysis` chunks; this avoids unbounded JS memory\n * growth in the hook without disabling native analysis processing.\n */\n keepFullAnalysis?: boolean\n\n /** iOS-specific configuration */\n ios?: IOSConfig\n\n /** Android-specific configuration */\n android?: AndroidConfig\n\n /** Web-specific configuration options */\n web?: WebConfig\n\n /** Duration of each segment in milliseconds for analysis (default: 100) */\n segmentDurationMs?: number\n\n /** Feature options to extract during audio processing */\n features?: AudioFeaturesOptions\n\n /** Callback function to handle audio stream data */\n onAudioStream?: (_: AudioDataEvent) => Promise<void>\n\n /** Callback function to handle audio features extraction results */\n onAudioAnalysis?: (_: AudioAnalysisEvent) => Promise<void>\n\n /**\n * Configuration for audio output files\n *\n * Examples:\n * - Primary only (default): `{ primary: { enabled: true } }`\n * - Compressed only: `{ primary: { enabled: false }, compressed: { enabled: true, format: 'aac' } }`\n * - Both outputs: `{ compressed: { enabled: true } }`\n * - Streaming only: `{ primary: { enabled: false } }`\n */\n output?: OutputConfig\n\n /** Whether to automatically resume recording after an interruption (default is false) */\n autoResumeAfterInterruption?: boolean\n\n /** Optional callback to handle recording interruptions */\n onRecordingInterrupted?: (_: RecordingInterruptionEvent) => void\n\n /**\n * Maximum cumulative active recording duration, in milliseconds.\n *\n * Paused time does not count. Set to undefined, 0, or a negative value to disable.\n */\n maxDurationMs?: number\n\n /**\n * Stop recording automatically when maxDurationMs is reached.\n *\n * Defaults to false. The MaxDurationReached event is emitted before the stop request.\n * The automatic stop result is not returned to onMaxDurationReached; use the\n * event and stream callbacks for immediate UI updates.\n */\n autoStopOnMaxDuration?: boolean\n\n /**\n * Optional callback invoked when maxDurationMs is reached.\n *\n * If autoStopOnMaxDuration is true, this callback is invoked before the\n * recorder finishes stopping. The final stop result is not passed here.\n */\n onMaxDurationReached?: (_: MaxDurationReachedEvent) => void\n\n /** Optional directory path where output files will be saved */\n outputDirectory?: string // If not provided, uses default app directory\n /** Optional filename for the recording (uses UUID if not provided) */\n filename?: string // If not provided, uses UUID\n\n /** ID of the device to use for recording (if not specified, uses default) */\n deviceId?: string\n\n /** How to handle device disconnection during recording */\n deviceDisconnectionBehavior?: DeviceDisconnectionBehaviorType\n\n /**\n * Buffer duration in seconds. Controls the size of audio buffers\n * used during recording. Smaller values reduce latency but increase\n * CPU usage. Larger values improve efficiency but increase latency.\n *\n * Platform Notes:\n * - iOS/macOS: Minimum effective 0.1s, uses accumulation below\n * - Android: Respects all sizes within hardware limits\n * - Web: Fully configurable\n *\n * Default: undefined (uses platform default ~23ms at 44.1kHz)\n * Recommended: 0.01 - 0.5 seconds\n * Optimal iOS: >= 0.1 seconds\n */\n bufferDurationSeconds?: number\n\n /**\n * Format for the audio stream data delivered to `onAudioStream`.\n *\n * - `'raw'` (default): base64-encoded PCM bytes on native, Float32Array on web\n * - `'float32'`: Float32Array with samples in [-1, 1] on all platforms.\n * Eliminates base64 encode/decode overhead on the native bridge.\n * Android (new arch): delivered as Float32Array via JSI.\n * iOS: delivered as regular Array<number>, normalized to Float32Array in JS.\n *\n * @default 'raw'\n */\n streamFormat?: 'float32' | 'raw'\n}\n\nexport interface NotificationConfig {\n /** Title of the notification */\n title?: string\n\n /** Main text content of the notification */\n text?: string\n\n /** Icon to be displayed in the notification (resource name or URI) */\n icon?: string\n\n /** Android-specific notification configuration */\n android?: {\n /** Unique identifier for the notification channel */\n channelId?: string\n\n /** User-visible name of the notification channel */\n channelName?: string\n\n /** User-visible description of the notification channel */\n channelDescription?: string\n\n /** Unique identifier for this notification */\n notificationId?: number\n\n /** List of actions that can be performed from the notification */\n actions?: NotificationAction[]\n\n /** Configuration for the waveform visualization in the notification */\n waveform?: WaveformConfig\n\n /** Color of the notification LED (if device supports it) */\n lightColor?: string\n\n /** Priority of the notification (affects how it's displayed) */\n priority?: 'min' | 'low' | 'default' | 'high' | 'max'\n\n /** Accent color for the notification (used for the app icon and buttons) */\n accentColor?: string\n\n /** Whether to show pause/resume actions in the notification (default: true) */\n showPauseResumeActions?: boolean\n }\n\n /** iOS-specific notification configuration */\n ios?: {\n /** Identifier for the notification category (used for grouping similar notifications) */\n categoryIdentifier?: string\n }\n}\n\nexport interface NotificationAction {\n /** Display title for the action */\n title: string\n\n /** Unique identifier for the action */\n identifier: string\n\n /** Icon to be displayed for the action (Android only) */\n icon?: string\n}\n\nexport interface WaveformConfig {\n /** The color of the waveform (e.g., \"#FFFFFF\" for white) */\n color?: string // The color of the waveform (e.g., \"#FFFFFF\" for white)\n /** Opacity of the waveform (0.0 - 1.0) */\n opacity?: number // Opacity of the waveform (0.0 - 1.0)\n /** Width of the waveform line (default: 1.5) */\n strokeWidth?: number // Width of the waveform line (default: 1.5)\n /** Drawing style: \"stroke\" for outline, \"fill\" for solid */\n style?: 'stroke' | 'fill' // Drawing style: \"stroke\" for outline, \"fill\" for solid\n /** Whether to mirror the waveform (symmetrical display) */\n mirror?: boolean // Whether to mirror the waveform (symmetrical display)\n /** Height of the waveform view in dp (default: 64) */\n height?: number // Height of the waveform view in dp (default: 64)\n}\n\nexport interface ExtractAudioDataOptions {\n /** URI of the audio file to extract data from */\n fileUri: string\n /** Start time in milliseconds (for time-based range) */\n startTimeMs?: number\n /** End time in milliseconds (for time-based range) */\n endTimeMs?: number\n /** Start position in bytes (for byte-based range) */\n position?: number\n /** Length in bytes to extract (for byte-based range) */\n length?: number\n /** Include normalized audio data in [-1, 1] range */\n includeNormalizedData?: boolean\n /** Include base64 encoded string representation of the audio data */\n includeBase64Data?: boolean\n /** Include WAV header in the PCM data (makes it a valid WAV file) */\n includeWavHeader?: boolean\n /** Logger for debugging - can pass console directly. */\n logger?: ConsoleLike\n /** Compute the checksum of the PCM data */\n computeChecksum?: boolean\n /** Target config for the normalized audio (Android and Web) */\n decodingOptions?: DecodingConfig\n}\n\nexport interface ExtractedAudioData {\n /** Raw PCM audio data */\n pcmData: Uint8Array\n /** Normalized audio data in [-1, 1] range (when includeNormalizedData is true) */\n normalizedData?: Float32Array\n /** Base64 encoded string representation of the audio data (when includeBase64Data is true) */\n base64Data?: string\n /** Sample rate in Hz (e.g., 44100, 48000) */\n sampleRate: number\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels: number\n /** Bits per sample (8, 16, or 32) */\n bitDepth: BitDepth\n /** Duration of the audio in milliseconds */\n durationMs: number\n /** PCM format identifier (e.g., \"pcm_16bit\") */\n format: PCMFormat\n /** Total number of audio samples per channel */\n samples: number\n /** Whether the pcmData includes a WAV header */\n hasWavHeader?: boolean\n /** CRC32 Checksum of PCM data */\n checksum?: number\n}\n\nexport interface UseAudioRecorderState {\n /**\n * Prepares recording with the specified configuration without starting it.\n *\n * This method eliminates the latency between calling startRecording and the actual recording beginning.\n * It pre-initializes all audio resources, requests permissions, and sets up audio sessions in advance,\n * allowing for true zero-latency recording start when startRecording is called later.\n *\n * Technical benefits:\n * - Eliminates audio pipeline initialization delay (50-300ms depending on platform)\n * - Pre-allocates audio buffers to avoid memory allocation during recording start\n * - Initializes audio hardware in advance (particularly important on iOS)\n * - Requests and verifies permissions before the critical recording moment\n *\n * Use this method when:\n * - You need zero-latency recording start (e.g., voice commands, musical applications)\n * - You're building time-sensitive applications where missing initial audio would be problematic\n * - You want to prepare resources during app initialization, screen loading, or preceding user interaction\n * - You need to ensure recording starts reliably and instantly on all platforms\n *\n * @param config - The recording configuration, identical to what you would pass to startRecording\n * @returns A promise that resolves when preparation is complete\n *\n * @example\n * // Prepare during component mounting\n * useEffect(() => {\n * prepareRecording({\n * sampleRate: 44100,\n * channels: 1,\n * encoding: 'pcm_16bit',\n * });\n * }, []);\n *\n * // Later when user taps record button, it starts with zero latency\n * const handleRecordPress = () => startRecording({\n * sampleRate: 44100,\n * channels: 1,\n * encoding: 'pcm_16bit',\n * });\n */\n prepareRecording: (_: RecordingConfig) => Promise<void>\n /** Starts recording with the specified configuration */\n startRecording: (_: RecordingConfig) => Promise<StartRecordingResult>\n /** Stops the current recording and returns the recording data */\n stopRecording: () => Promise<AudioRecording | null>\n /** Pauses the current recording */\n pauseRecording: () => Promise<void>\n /** Resumes a paused recording */\n resumeRecording: () => Promise<void>\n /** Indicates whether recording is currently active */\n isRecording: boolean\n /** Indicates whether recording is in a paused state */\n isPaused: boolean\n /** Duration of the current recording in milliseconds */\n durationMs: number // Duration of the recording\n /** Size of the recorded audio in bytes */\n size: number // Size in bytes of the recorded audio\n /** Information about compression if enabled */\n compression?: CompressionInfo\n /** Configured maximum active recording duration in milliseconds, if enabled */\n maxDurationMs?: number\n /** Whether the current recording session has reached the configured maximum duration */\n maxDurationReached?: boolean\n /** Analysis data for the recording if processing was enabled */\n analysisData?: AudioAnalysis // Analysis data for the recording depending on enableProcessing flag\n /** Optional callback to handle recording interruptions */\n onRecordingInterrupted?: (_: RecordingInterruptionEvent) => void\n /** Optional callback invoked when maxDurationMs is reached */\n onMaxDurationReached?: (_: MaxDurationReachedEvent) => void\n}\n\n/**\n * Represents an event emitted during the trimming process to report progress.\n */\nexport interface TrimProgressEvent {\n /**\n * The percentage of the trimming process that has been completed, ranging from 0 to 100.\n */\n progress: number\n\n /**\n * The number of bytes that have been processed so far. This is optional and may not be provided in all implementations.\n */\n bytesProcessed?: number\n\n /**\n * The total number of bytes to process. This is optional and may not be provided in all implementations.\n */\n totalBytes?: number\n}\n\n/**\n * Defines a time range in milliseconds for trimming operations.\n */\nexport interface TimeRange {\n /**\n * The start time of the range in milliseconds.\n */\n startTimeMs: number\n\n /**\n * The end time of the range in milliseconds.\n */\n endTimeMs: number\n}\n\n/**\n * Options for configuring the audio trimming operation.\n */\nexport interface TrimAudioOptions {\n /**\n * The URI of the audio file to trim.\n */\n fileUri: string\n\n /**\n * The mode of trimming to apply.\n * - `'single'`: Trims the audio to a single range defined by `startTimeMs` and `endTimeMs`.\n * - `'keep'`: Keeps the specified `ranges` and removes all other portions of the audio.\n * - `'remove'`: Removes the specified `ranges` and keeps the remaining portions of the audio.\n * @default 'single'\n */\n mode?: 'single' | 'keep' | 'remove'\n\n /**\n * An array of time ranges to keep or remove, depending on the `mode`.\n * - Required for `'keep'` and `'remove'` modes.\n * - Ignored when `mode` is `'single'`.\n */\n ranges?: TimeRange[]\n\n /**\n * The start time in milliseconds for the `'single'` mode.\n * - If not provided, trimming starts from the beginning of the audio (0 ms).\n */\n startTimeMs?: number\n\n /**\n * The end time in milliseconds for the `'single'` mode.\n * - If not provided, trimming extends to the end of the audio.\n */\n endTimeMs?: number\n\n /**\n * The name of the output file. If not provided, a default name will be generated.\n */\n outputFileName?: string\n\n /**\n * Configuration for the output audio format.\n */\n outputFormat?: {\n /**\n * The format of the output audio file.\n * - `'wav'`: Waveform Audio File Format (uncompressed).\n * - `'aac'`: Advanced Audio Coding (compressed). Not supported on web platforms.\n * - `'opus'`: Opus Interactive Audio Codec (compressed).\n */\n format: 'wav' | 'aac' | 'opus'\n\n /**\n * The sample rate of the output audio in Hertz (Hz).\n * - If not provided, the input audio's sample rate is used.\n */\n sampleRate?: number\n\n /**\n * The number of channels in the output audio (e.g., 1 for mono, 2 for stereo).\n * - If not provided, the input audio's channel count is used.\n */\n channels?: number\n\n /**\n * The bit depth of the output audio, applicable to PCM formats like `'wav'`.\n * - If not provided, the input audio's bit depth is used.\n */\n bitDepth?: number\n\n /**\n * The bitrate of the output audio in bits per second, applicable to compressed formats like `'aac'`.\n * - If not provided, a default bitrate is used based on the format.\n */\n bitrate?: number\n }\n\n /**\n * Options for decoding the input audio file.\n * - See `DecodingConfig` for details.\n */\n decodingOptions?: DecodingConfig\n}\n\n/**\n * Result of the audio trimming operation.\n */\nexport interface TrimAudioResult {\n /**\n * The URI of the trimmed audio file.\n */\n uri: string\n\n /**\n * The filename of the trimmed audio file.\n */\n filename: string\n\n /**\n * The duration of the trimmed audio in milliseconds.\n */\n durationMs: number\n\n /**\n * The size of the trimmed audio file in bytes.\n */\n size: number\n\n /**\n * The sample rate of the trimmed audio in Hertz (Hz).\n */\n sampleRate: number\n\n /**\n * The number of channels in the trimmed audio (e.g., 1 for mono, 2 for stereo).\n */\n channels: number\n\n /**\n * The bit depth of the trimmed audio, applicable to PCM formats like `'wav'`.\n */\n bitDepth: number\n\n /**\n * The MIME type of the trimmed audio file (e.g., `'audio/wav'`, `'audio/mpeg'`).\n */\n mimeType: string\n\n /**\n * Information about compression if the output format is compressed.\n */\n compression?: {\n /**\n * The format of the compression (e.g., `'aac'`, `'mp3'`, `'opus'`).\n */\n format: string\n\n /**\n * The bitrate of the compressed audio in bits per second.\n */\n bitrate: number\n\n /**\n * The size of the compressed audio file in bytes.\n */\n size: number\n }\n\n /**\n * Information about the processing time.\n */\n processingInfo?: {\n /**\n * The time it took to process the audio in milliseconds.\n */\n durationMs: number\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AudioStudio.types.js","sourceRoot":"","sources":["../../src/AudioStudio.types.ts"],"names":[],"mappings":"AAiWA,4EAA4E;AAC5E,MAAM,CAAC,MAAM,2BAA2B,GAAG;IACvC,8CAA8C;IAC9C,KAAK,EAAE,OAAO;IACd,sDAAsD;IACtD,QAAQ,EAAE,UAAU;CACd,CAAA","sourcesContent":["// packages/audio-studio/src/AudioStudio.types.ts\nimport {\n AudioAnalysis,\n AudioFeaturesOptions,\n DecodingConfig,\n} from './AudioAnalysis/AudioAnalysis.types'\nimport type { AudioAnalysisEvent } from './events'\n\nexport interface CompressionInfo {\n /** Size of the compressed audio data in bytes */\n size: number\n /** MIME type of the compressed audio (e.g., 'audio/aac', 'audio/opus') */\n mimeType: string\n /** Bitrate of the compressed audio in bits per second */\n bitrate: number\n /** Format of the compression (e.g., 'aac', 'opus') */\n format: string\n /** URI to the compressed audio file if available */\n compressedFileUri?: string\n}\n\nexport interface AudioStreamStatus {\n /** Indicates whether audio recording is currently active */\n isRecording: boolean\n /** Indicates whether recording is in a paused state */\n isPaused: boolean\n /** Duration of the current recording in milliseconds */\n durationMs: number\n /** Size of the recorded audio data in bytes */\n size: number\n /** Interval in milliseconds at which recording data is emitted */\n interval: number\n /** Interval in milliseconds at which analysis data is emitted */\n intervalAnalysis: number\n /** MIME type of the recorded audio (e.g., 'audio/wav') */\n mimeType: string\n /** Information about audio compression if enabled */\n compression?: CompressionInfo\n /** Configured maximum active recording duration in milliseconds, if enabled */\n maxDurationMs?: number\n /** Whether the current recording session has reached the configured maximum duration */\n maxDurationReached?: boolean\n}\n\ninterface AudioDataEventBase {\n /** Current position in the audio stream in bytes */\n position: number\n /** URI to the file being recorded */\n fileUri: string\n /** Size of the current data chunk in bytes */\n eventDataSize: number\n /** Total size of the recording so far in bytes */\n totalSize: number\n /** Information about compression if enabled, including the compressed data chunk */\n compression?: CompressionInfo & {\n /** Base64 (native) or Blob (web) encoded compressed data chunk */\n data?: string | Blob\n }\n}\n\nexport interface AudioDataEventRaw extends AudioDataEventBase {\n /** Audio data as base64 string (native), Float32Array (web), or Int16Array (web) */\n data: string | Float32Array | Int16Array\n streamFormat?: undefined | 'raw'\n}\n\nexport interface AudioDataEventFloat32 extends AudioDataEventBase {\n /** Audio data as Float32Array with samples in [-1, 1] range */\n data: Float32Array\n streamFormat: 'float32'\n}\n\nexport type AudioDataEvent = AudioDataEventRaw | AudioDataEventFloat32\n\n/**\n * Audio encoding types supported by the library.\n *\n * Platform support:\n * - `pcm_8bit`: Android only (iOS/Web will fallback to 16-bit)\n * - `pcm_16bit`: All platforms\n * - `pcm_32bit`: All platforms\n *\n * @see {@link https://github.com/deeeed/audiolab/blob/main/packages/audio-studio/docs/PLATFORM_LIMITATIONS.md | Platform Limitations}\n */\nexport type EncodingType = 'pcm_32bit' | 'pcm_16bit' | 'pcm_8bit'\n\n/**\n * Supported audio sample rates in Hz.\n * All platforms support these standard rates.\n */\nexport type SampleRate = 16000 | 44100 | 48000\n\n/**\n * Audio bit depth (bits per sample).\n *\n * Platform support:\n * - `8`: Android only (iOS/Web will fallback to 16)\n * - `16`: All platforms (recommended for compatibility)\n * - `32`: All platforms\n *\n * @see {@link https://github.com/deeeed/audiolab/blob/main/packages/audio-studio/docs/PLATFORM_LIMITATIONS.md | Platform Limitations}\n */\nexport type BitDepth = 8 | 16 | 32\n\n/**\n * PCM format string representation.\n * @deprecated Use `EncodingType` directly\n */\nexport type PCMFormat = `pcm_${BitDepth}bit`\n\nexport type ConsoleLike = {\n /** Logs a message with optional arguments */\n log: (message: string, ...args: unknown[]) => void\n /** Logs a debug message with optional arguments */\n debug: (message: string, ...args: unknown[]) => void\n /** Logs an info message with optional arguments */\n info: (message: string, ...args: unknown[]) => void\n /** Logs a warning message with optional arguments */\n warn: (message: string, ...args: unknown[]) => void\n /** Logs an error message with optional arguments */\n error: (message: string, ...args: unknown[]) => void\n}\n\nexport interface Chunk {\n /** Transcribed text content */\n text: string\n /** Start and end timestamp in seconds [start, end] where end can be null if ongoing */\n timestamp: [number, number | null]\n}\n\nexport interface TranscriberData {\n /** Unique identifier for the transcription */\n id: string\n /** Indicates if the transcriber is currently processing */\n isBusy: boolean\n /** Complete transcribed text */\n text: string\n /** Start time of the transcription in milliseconds */\n startTime: number\n /** End time of the transcription in milliseconds */\n endTime: number\n /** Array of transcribed text chunks with timestamps */\n chunks: Chunk[]\n}\n\nexport interface AudioRecording {\n /** URI to the recorded audio file */\n fileUri: string\n /** Filename of the recorded audio */\n filename: string\n /** Duration of the recording in milliseconds */\n durationMs: number\n /** Size of the recording in bytes */\n size: number\n /** MIME type of the recorded audio */\n mimeType: string\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels: number\n /** Bit depth of the audio (8, 16, or 32 bits) */\n bitDepth: BitDepth\n /** Sample rate of the audio in Hz */\n sampleRate: SampleRate\n /** Timestamp when the recording was created */\n createdAt?: number\n /** Array of transcription data if available */\n transcripts?: TranscriberData[]\n /**\n * Full analysis data for the recording if processing was enabled and\n * `keepFullAnalysis` was not set to `false`.\n */\n analysisData?: AudioAnalysis\n /** Information about compression if enabled, including the URI to the compressed file */\n compression?: CompressionInfo & {\n /** URI to the compressed audio file */\n compressedFileUri: string\n }\n}\n\nexport interface StartRecordingResult {\n /** URI to the file being recorded */\n fileUri: string\n /** MIME type of the recording */\n mimeType: string\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels?: number\n /** Bit depth of the audio (8, 16, or 32 bits) */\n bitDepth?: BitDepth\n /** Sample rate of the audio in Hz */\n sampleRate?: SampleRate\n /** Information about compression if enabled, including the URI to the compressed file */\n compression?: CompressionInfo & {\n /** URI to the compressed audio file */\n compressedFileUri: string\n }\n}\n\nexport interface MaxDurationReachedEvent {\n /** Active recording duration that triggered the event, in milliseconds */\n durationMs: number\n /** Configured active recording duration limit, in milliseconds */\n maxDurationMs: number\n /** Amount by which timer delivery exceeded the limit, in milliseconds */\n overrunMs: number\n /** Active stream identifier when available */\n streamUuid?: string\n /** Whether the recorder was configured to stop automatically after this event */\n autoStopped: boolean\n}\n\nexport type RecordingStopReason = 'manual' | 'maxDuration'\n\nexport interface AudioSessionConfig {\n /**\n * Audio session category that defines the audio behavior\n * - 'Ambient': Audio continues with silent switch, mixes with other audio\n * - 'SoloAmbient': Audio continues with silent switch, interrupts other audio\n * - 'Playback': Audio continues in background, interrupts other audio\n * - 'Record': Optimized for recording, interrupts other audio\n * - 'PlayAndRecord': Allows simultaneous playback and recording\n * - 'MultiRoute': Routes audio to multiple outputs simultaneously\n */\n category?:\n | 'Ambient'\n | 'SoloAmbient'\n | 'Playback'\n | 'Record'\n | 'PlayAndRecord'\n | 'MultiRoute'\n /**\n * Audio session mode that defines the behavior for specific use cases\n * - 'Default': Standard audio behavior\n * - 'VoiceChat': Optimized for voice chat applications\n * - 'VideoChat': Optimized for video chat applications\n * - 'GameChat': Optimized for in-game chat\n * - 'VideoRecording': Optimized for video recording\n * - 'Measurement': Optimized for audio measurement\n * - 'MoviePlayback': Optimized for movie playback\n * - 'SpokenAudio': Optimized for spoken audio content\n */\n mode?:\n | 'Default'\n | 'VoiceChat'\n | 'VideoChat'\n | 'GameChat'\n | 'VideoRecording'\n | 'Measurement'\n | 'MoviePlayback'\n | 'SpokenAudio'\n /**\n * Options that modify the behavior of the audio session category\n * - 'MixWithOthers': Allows mixing with other active audio sessions\n * - 'DuckOthers': Reduces the volume of other audio sessions\n * - 'InterruptSpokenAudioAndMixWithOthers': Interrupts spoken audio and mixes with others\n * - 'AllowBluetooth': Allows audio routing to Bluetooth devices\n * - 'AllowBluetoothA2DP': Allows audio routing to Bluetooth A2DP devices\n * - 'AllowAirPlay': Allows audio routing to AirPlay devices\n * - 'DefaultToSpeaker': Routes audio to the speaker by default\n */\n categoryOptions?: (\n | 'MixWithOthers'\n | 'DuckOthers'\n | 'InterruptSpokenAudioAndMixWithOthers'\n | 'AllowBluetooth'\n | 'AllowBluetoothA2DP'\n | 'AllowAirPlay'\n | 'DefaultToSpeaker'\n )[]\n}\n\nexport interface IOSConfig {\n /** Configuration for the iOS audio session */\n audioSession?: AudioSessionConfig\n}\n\n/** Android platform specific configuration options */\nexport interface AndroidConfig {\n /**\n * Audio focus strategy for handling interruptions and background behavior\n *\n * - `'background'`: Continue recording when app loses focus (voice recorders, transcription apps)\n * - `'interactive'`: Pause when losing focus, resume when gaining (music apps, games)\n * - `'communication'`: Maintain priority for real-time communication (video calls, voice chat)\n * - `'none'`: No automatic audio focus management (custom handling)\n *\n * @default 'background' when keepAwake=true, 'interactive' otherwise\n */\n audioFocusStrategy?: 'background' | 'interactive' | 'communication' | 'none'\n}\n\n/** Web platform specific configuration options */\nexport interface WebConfig {\n // Reserved for future web-specific options\n}\n\n// Add new type for interruption reasons\nexport type RecordingInterruptionReason =\n /** Audio focus was lost to another app */\n | 'audioFocusLoss'\n /** Audio focus was regained */\n | 'audioFocusGain'\n /** Recording was interrupted by a phone call */\n | 'phoneCall'\n /** Phone call that interrupted recording has ended */\n | 'phoneCallEnded'\n /** Recording was stopped by the system or another app */\n | 'recordingStopped'\n /** Recording device was disconnected */\n | 'deviceDisconnected'\n /** Recording switched to default device after disconnection */\n | 'deviceFallback'\n /** A new audio device was connected */\n | 'deviceConnected'\n /** Device switching failed */\n | 'deviceSwitchFailed'\n\n// Add new interface for interruption events\nexport interface RecordingInterruptionEvent {\n /** The reason for the recording interruption */\n reason: RecordingInterruptionReason\n /** Indicates whether the recording is paused due to the interruption */\n isPaused: boolean\n}\n\nexport interface AudioDeviceCapabilities {\n /** Supported sample rates for the device */\n sampleRates: number[]\n /** Supported channel counts for the device */\n channelCounts: number[]\n /** Supported bit depths for the device */\n bitDepths: number[]\n /** Whether the device supports echo cancellation */\n hasEchoCancellation?: boolean\n /** Whether the device supports noise suppression */\n hasNoiseSuppression?: boolean\n /** Whether the device supports automatic gain control */\n hasAutomaticGainControl?: boolean\n}\n\nexport interface AudioDevice {\n /** Unique identifier for the device */\n id: string\n /** Human-readable name of the device */\n name: string\n /** Device type (builtin_mic, bluetooth, etc.) */\n type: string\n /** Whether this is the system default device */\n isDefault: boolean\n /** Audio capabilities for the device */\n capabilities: AudioDeviceCapabilities\n /** Whether the device is currently available */\n isAvailable: boolean\n}\n\n/** Defines how recording should behave when a device becomes unavailable */\nexport const DeviceDisconnectionBehavior = {\n /** Pause recording when device disconnects */\n PAUSE: 'pause',\n /** Switch to default device and continue recording */\n FALLBACK: 'fallback',\n} as const\n\n/** Type for DeviceDisconnectionBehavior values */\nexport type DeviceDisconnectionBehaviorType =\n (typeof DeviceDisconnectionBehavior)[keyof typeof DeviceDisconnectionBehavior]\n\n/**\n * Configuration for audio output files during recording\n */\nexport interface OutputConfig {\n /**\n * Configuration for the primary (uncompressed) output file\n */\n primary?: {\n /** Whether to create the primary output file (default: true) */\n enabled?: boolean\n /** Format for the primary output (currently only 'wav' is supported) */\n format?: 'wav'\n }\n\n /**\n * Configuration for the compressed output file\n */\n compressed?: {\n /** Whether to create a compressed output file (default: false) */\n enabled?: boolean\n /**\n * Format for compression\n * - 'aac': Advanced Audio Coding - supported on all platforms\n * - 'opus': Opus encoding - supported on Android and Web; on iOS will automatically fall back to AAC\n */\n format?: 'aac' | 'opus'\n /** Bitrate for compression in bits per second (default: 128000) */\n bitrate?: number\n /**\n * Prefer raw stream over container format (Android only)\n * - true: Use raw AAC stream (.aac files) like in v2.10.6\n * - false/undefined: Use M4A container (.m4a files) for better seeking support\n * Note: iOS always produces M4A containers and ignores this flag\n */\n preferRawStream?: boolean\n }\n\n // Future enhancement: Post-processing pipeline\n // postProcessing?: {\n // normalize?: boolean\n // trimSilence?: boolean\n // noiseReduction?: boolean\n // customProcessors?: AudioProcessor[]\n // }\n}\n\nexport interface RecordingConfig {\n /** Sample rate for recording in Hz (16000, 44100, or 48000) */\n sampleRate?: SampleRate\n\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels?: 1 | 2\n\n /**\n * Encoding type for the recording.\n *\n * Platform limitations:\n * - `pcm_8bit`: Android only (iOS/Web will fallback to `pcm_16bit` with warning)\n * - `pcm_16bit`: All platforms (recommended for cross-platform compatibility)\n * - `pcm_32bit`: All platforms\n *\n * The library will automatically validate and adjust the encoding based on\n * platform capabilities. A warning will be logged if fallback is required.\n *\n * @default 'pcm_16bit'\n * @see {@link EncodingType}\n * @see {@link https://github.com/deeeed/audiolab/blob/main/packages/audio-studio/docs/PLATFORM_LIMITATIONS.md | Platform Limitations}\n */\n encoding?: EncodingType\n\n /** Interval in milliseconds at which to emit recording data (minimum: 10ms) */\n interval?: number\n\n /** Interval in milliseconds at which to emit analysis data (minimum: 10ms) */\n intervalAnalysis?: number\n\n /** Keep the device awake while recording (default is false) */\n keepAwake?: boolean\n\n /** Show a notification during recording (default is false) */\n showNotification?: boolean\n\n /** Show waveform in the notification (Android only, when showNotification is true) */\n showWaveformInNotification?: boolean\n\n /** Configuration for the notification */\n notification?: NotificationConfig\n\n /** Enable audio processing (default is false) */\n enableProcessing?: boolean\n\n /**\n * Whether `useAudioRecorder` should retain every audio-analysis data point\n * and attach the full history to `stopRecording().analysisData`.\n *\n * Defaults to `true` for backwards compatibility. Set to `false` for\n * long-running recordings when you only need live `analysisData` state or\n * per-callback `onAudioAnalysis` chunks; this avoids unbounded JS memory\n * growth in the hook without disabling native analysis processing.\n */\n keepFullAnalysis?: boolean\n\n /** iOS-specific configuration */\n ios?: IOSConfig\n\n /** Android-specific configuration */\n android?: AndroidConfig\n\n /** Web-specific configuration options */\n web?: WebConfig\n\n /** Duration of each segment in milliseconds for analysis (default: 100) */\n segmentDurationMs?: number\n\n /** Feature options to extract during audio processing */\n features?: AudioFeaturesOptions\n\n /** Callback function to handle audio stream data */\n onAudioStream?: (_: AudioDataEvent) => Promise<void>\n\n /** Callback function to handle audio features extraction results */\n onAudioAnalysis?: (_: AudioAnalysisEvent) => Promise<void>\n\n /**\n * Configuration for audio output files\n *\n * Examples:\n * - Primary only (default): `{ primary: { enabled: true } }`\n * - Compressed only: `{ primary: { enabled: false }, compressed: { enabled: true, format: 'aac' } }`\n * - Both outputs: `{ compressed: { enabled: true } }`\n * - Streaming only: `{ primary: { enabled: false } }`\n */\n output?: OutputConfig\n\n /** Whether to automatically resume recording after an interruption (default is false) */\n autoResumeAfterInterruption?: boolean\n\n /** Optional callback to handle recording interruptions */\n onRecordingInterrupted?: (_: RecordingInterruptionEvent) => void\n\n /**\n * Maximum cumulative active recording duration, in milliseconds.\n *\n * Paused time does not count. Set to undefined, 0, or a negative value to disable.\n */\n maxDurationMs?: number\n\n /**\n * Stop recording automatically when maxDurationMs is reached.\n *\n * Defaults to false. When used with `useAudioRecorder`, the\n * MaxDurationReached event is emitted immediately, then the hook stops the\n * recorder and exposes the final result through `onRecordingStopped`.\n */\n autoStopOnMaxDuration?: boolean\n\n /**\n * Optional callback invoked when maxDurationMs is reached.\n *\n * This remains an immediate threshold callback. If\n * autoStopOnMaxDuration is true, use `onRecordingStopped` for the full\n * recording result after stop completes.\n */\n onMaxDurationReached?: (_: MaxDurationReachedEvent) => void\n\n /**\n * Optional callback invoked after a recording has fully stopped and the\n * final `AudioRecording` result is available.\n *\n * The reason is `manual` when stopped through `stopRecording()` and\n * `maxDuration` when stopped by `autoStopOnMaxDuration`.\n */\n onRecordingStopped?: (\n recording: AudioRecording,\n reason: RecordingStopReason\n ) => void | Promise<void>\n\n /** Optional directory path where output files will be saved */\n outputDirectory?: string // If not provided, uses default app directory\n /** Optional filename for the recording (uses UUID if not provided) */\n filename?: string // If not provided, uses UUID\n\n /** ID of the device to use for recording (if not specified, uses default) */\n deviceId?: string\n\n /** How to handle device disconnection during recording */\n deviceDisconnectionBehavior?: DeviceDisconnectionBehaviorType\n\n /**\n * Buffer duration in seconds. Controls the size of audio buffers\n * used during recording. Smaller values reduce latency but increase\n * CPU usage. Larger values improve efficiency but increase latency.\n *\n * Platform Notes:\n * - iOS/macOS: Minimum effective 0.1s, uses accumulation below\n * - Android: Respects all sizes within hardware limits\n * - Web: Fully configurable\n *\n * Default: undefined (uses platform default ~23ms at 44.1kHz)\n * Recommended: 0.01 - 0.5 seconds\n * Optimal iOS: >= 0.1 seconds\n */\n bufferDurationSeconds?: number\n\n /**\n * Format for the audio stream data delivered to `onAudioStream`.\n *\n * - `'raw'` (default): base64-encoded PCM bytes on native, Float32Array on web\n * - `'float32'`: Float32Array with samples in [-1, 1] on all platforms.\n * Eliminates base64 encode/decode overhead on the native bridge.\n * Android (new arch): delivered as Float32Array via JSI.\n * iOS: delivered as regular Array<number>, normalized to Float32Array in JS.\n *\n * @default 'raw'\n */\n streamFormat?: 'float32' | 'raw'\n}\n\nexport interface NotificationConfig {\n /** Title of the notification */\n title?: string\n\n /** Main text content of the notification */\n text?: string\n\n /** Icon to be displayed in the notification (resource name or URI) */\n icon?: string\n\n /** Android-specific notification configuration */\n android?: {\n /** Unique identifier for the notification channel */\n channelId?: string\n\n /** User-visible name of the notification channel */\n channelName?: string\n\n /** User-visible description of the notification channel */\n channelDescription?: string\n\n /** Unique identifier for this notification */\n notificationId?: number\n\n /** List of actions that can be performed from the notification */\n actions?: NotificationAction[]\n\n /** Configuration for the waveform visualization in the notification */\n waveform?: WaveformConfig\n\n /** Color of the notification LED (if device supports it) */\n lightColor?: string\n\n /** Priority of the notification (affects how it's displayed) */\n priority?: 'min' | 'low' | 'default' | 'high' | 'max'\n\n /** Accent color for the notification (used for the app icon and buttons) */\n accentColor?: string\n\n /** Whether to show pause/resume actions in the notification (default: true) */\n showPauseResumeActions?: boolean\n }\n\n /** iOS-specific notification configuration */\n ios?: {\n /** Identifier for the notification category (used for grouping similar notifications) */\n categoryIdentifier?: string\n }\n}\n\nexport interface NotificationAction {\n /** Display title for the action */\n title: string\n\n /** Unique identifier for the action */\n identifier: string\n\n /** Icon to be displayed for the action (Android only) */\n icon?: string\n}\n\nexport interface WaveformConfig {\n /** The color of the waveform (e.g., \"#FFFFFF\" for white) */\n color?: string // The color of the waveform (e.g., \"#FFFFFF\" for white)\n /** Opacity of the waveform (0.0 - 1.0) */\n opacity?: number // Opacity of the waveform (0.0 - 1.0)\n /** Width of the waveform line (default: 1.5) */\n strokeWidth?: number // Width of the waveform line (default: 1.5)\n /** Drawing style: \"stroke\" for outline, \"fill\" for solid */\n style?: 'stroke' | 'fill' // Drawing style: \"stroke\" for outline, \"fill\" for solid\n /** Whether to mirror the waveform (symmetrical display) */\n mirror?: boolean // Whether to mirror the waveform (symmetrical display)\n /** Height of the waveform view in dp (default: 64) */\n height?: number // Height of the waveform view in dp (default: 64)\n}\n\nexport interface ExtractAudioDataOptions {\n /** URI of the audio file to extract data from */\n fileUri: string\n /** Start time in milliseconds (for time-based range) */\n startTimeMs?: number\n /** End time in milliseconds (for time-based range) */\n endTimeMs?: number\n /** Start position in bytes (for byte-based range) */\n position?: number\n /** Length in bytes to extract (for byte-based range) */\n length?: number\n /** Include normalized audio data in [-1, 1] range */\n includeNormalizedData?: boolean\n /** Include base64 encoded string representation of the audio data */\n includeBase64Data?: boolean\n /** Include WAV header in the PCM data (makes it a valid WAV file) */\n includeWavHeader?: boolean\n /** Logger for debugging - can pass console directly. */\n logger?: ConsoleLike\n /** Compute the checksum of the PCM data */\n computeChecksum?: boolean\n /** Target config for the normalized audio (Android and Web) */\n decodingOptions?: DecodingConfig\n}\n\nexport interface ExtractedAudioData {\n /** Raw PCM audio data */\n pcmData: Uint8Array\n /** Normalized audio data in [-1, 1] range (when includeNormalizedData is true) */\n normalizedData?: Float32Array\n /** Base64 encoded string representation of the audio data (when includeBase64Data is true) */\n base64Data?: string\n /** Sample rate in Hz (e.g., 44100, 48000) */\n sampleRate: number\n /** Number of audio channels (1 for mono, 2 for stereo) */\n channels: number\n /** Bits per sample (8, 16, or 32) */\n bitDepth: BitDepth\n /** Duration of the audio in milliseconds */\n durationMs: number\n /** PCM format identifier (e.g., \"pcm_16bit\") */\n format: PCMFormat\n /** Total number of audio samples per channel */\n samples: number\n /** Whether the pcmData includes a WAV header */\n hasWavHeader?: boolean\n /** CRC32 Checksum of PCM data */\n checksum?: number\n}\n\nexport interface UseAudioRecorderState {\n /**\n * Prepares recording with the specified configuration without starting it.\n *\n * This method eliminates the latency between calling startRecording and the actual recording beginning.\n * It pre-initializes all audio resources, requests permissions, and sets up audio sessions in advance,\n * allowing for true zero-latency recording start when startRecording is called later.\n *\n * Technical benefits:\n * - Eliminates audio pipeline initialization delay (50-300ms depending on platform)\n * - Pre-allocates audio buffers to avoid memory allocation during recording start\n * - Initializes audio hardware in advance (particularly important on iOS)\n * - Requests and verifies permissions before the critical recording moment\n *\n * Use this method when:\n * - You need zero-latency recording start (e.g., voice commands, musical applications)\n * - You're building time-sensitive applications where missing initial audio would be problematic\n * - You want to prepare resources during app initialization, screen loading, or preceding user interaction\n * - You need to ensure recording starts reliably and instantly on all platforms\n *\n * @param config - The recording configuration, identical to what you would pass to startRecording\n * @returns A promise that resolves when preparation is complete\n *\n * @example\n * // Prepare during component mounting\n * useEffect(() => {\n * prepareRecording({\n * sampleRate: 44100,\n * channels: 1,\n * encoding: 'pcm_16bit',\n * });\n * }, []);\n *\n * // Later when user taps record button, it starts with zero latency\n * const handleRecordPress = () => startRecording({\n * sampleRate: 44100,\n * channels: 1,\n * encoding: 'pcm_16bit',\n * });\n */\n prepareRecording: (_: RecordingConfig) => Promise<void>\n /** Starts recording with the specified configuration */\n startRecording: (_: RecordingConfig) => Promise<StartRecordingResult>\n /** Stops the current recording and returns the recording data */\n stopRecording: () => Promise<AudioRecording | null>\n /** Pauses the current recording */\n pauseRecording: () => Promise<void>\n /** Resumes a paused recording */\n resumeRecording: () => Promise<void>\n /** Indicates whether recording is currently active */\n isRecording: boolean\n /** Indicates whether recording is in a paused state */\n isPaused: boolean\n /** Duration of the current recording in milliseconds */\n durationMs: number // Duration of the recording\n /** Size of the recorded audio in bytes */\n size: number // Size in bytes of the recorded audio\n /** Information about compression if enabled */\n compression?: CompressionInfo\n /** Configured maximum active recording duration in milliseconds, if enabled */\n maxDurationMs?: number\n /** Whether the current recording session has reached the configured maximum duration */\n maxDurationReached?: boolean\n /** Analysis data for the recording if processing was enabled */\n analysisData?: AudioAnalysis // Analysis data for the recording depending on enableProcessing flag\n /** Reason associated with the last completed recording */\n lastRecordingReason?: RecordingStopReason\n /** Optional callback to handle recording interruptions */\n onRecordingInterrupted?: (_: RecordingInterruptionEvent) => void\n /** Optional callback invoked when maxDurationMs is reached */\n onMaxDurationReached?: (_: MaxDurationReachedEvent) => void\n /** Optional callback invoked when a recording fully stops */\n onRecordingStopped?: (\n recording: AudioRecording,\n reason: RecordingStopReason\n ) => void | Promise<void>\n}\n\n/**\n * Represents an event emitted during the trimming process to report progress.\n */\nexport interface TrimProgressEvent {\n /**\n * The percentage of the trimming process that has been completed, ranging from 0 to 100.\n */\n progress: number\n\n /**\n * The number of bytes that have been processed so far. This is optional and may not be provided in all implementations.\n */\n bytesProcessed?: number\n\n /**\n * The total number of bytes to process. This is optional and may not be provided in all implementations.\n */\n totalBytes?: number\n}\n\n/**\n * Defines a time range in milliseconds for trimming operations.\n */\nexport interface TimeRange {\n /**\n * The start time of the range in milliseconds.\n */\n startTimeMs: number\n\n /**\n * The end time of the range in milliseconds.\n */\n endTimeMs: number\n}\n\n/**\n * Options for configuring the audio trimming operation.\n */\nexport interface TrimAudioOptions {\n /**\n * The URI of the audio file to trim.\n */\n fileUri: string\n\n /**\n * The mode of trimming to apply.\n * - `'single'`: Trims the audio to a single range defined by `startTimeMs` and `endTimeMs`.\n * - `'keep'`: Keeps the specified `ranges` and removes all other portions of the audio.\n * - `'remove'`: Removes the specified `ranges` and keeps the remaining portions of the audio.\n * @default 'single'\n */\n mode?: 'single' | 'keep' | 'remove'\n\n /**\n * An array of time ranges to keep or remove, depending on the `mode`.\n * - Required for `'keep'` and `'remove'` modes.\n * - Ignored when `mode` is `'single'`.\n */\n ranges?: TimeRange[]\n\n /**\n * The start time in milliseconds for the `'single'` mode.\n * - If not provided, trimming starts from the beginning of the audio (0 ms).\n */\n startTimeMs?: number\n\n /**\n * The end time in milliseconds for the `'single'` mode.\n * - If not provided, trimming extends to the end of the audio.\n */\n endTimeMs?: number\n\n /**\n * The name of the output file. If not provided, a default name will be generated.\n */\n outputFileName?: string\n\n /**\n * Configuration for the output audio format.\n */\n outputFormat?: {\n /**\n * The format of the output audio file.\n * - `'wav'`: Waveform Audio File Format (uncompressed).\n * - `'aac'`: Advanced Audio Coding (compressed). Not supported on web platforms.\n * - `'opus'`: Opus Interactive Audio Codec (compressed).\n */\n format: 'wav' | 'aac' | 'opus'\n\n /**\n * The sample rate of the output audio in Hertz (Hz).\n * - If not provided, the input audio's sample rate is used.\n */\n sampleRate?: number\n\n /**\n * The number of channels in the output audio (e.g., 1 for mono, 2 for stereo).\n * - If not provided, the input audio's channel count is used.\n */\n channels?: number\n\n /**\n * The bit depth of the output audio, applicable to PCM formats like `'wav'`.\n * - If not provided, the input audio's bit depth is used.\n */\n bitDepth?: number\n\n /**\n * The bitrate of the output audio in bits per second, applicable to compressed formats like `'aac'`.\n * - If not provided, a default bitrate is used based on the format.\n */\n bitrate?: number\n }\n\n /**\n * Options for decoding the input audio file.\n * - See `DecodingConfig` for details.\n */\n decodingOptions?: DecodingConfig\n}\n\n/**\n * Result of the audio trimming operation.\n */\nexport interface TrimAudioResult {\n /**\n * The URI of the trimmed audio file.\n */\n uri: string\n\n /**\n * The filename of the trimmed audio file.\n */\n filename: string\n\n /**\n * The duration of the trimmed audio in milliseconds.\n */\n durationMs: number\n\n /**\n * The size of the trimmed audio file in bytes.\n */\n size: number\n\n /**\n * The sample rate of the trimmed audio in Hertz (Hz).\n */\n sampleRate: number\n\n /**\n * The number of channels in the trimmed audio (e.g., 1 for mono, 2 for stereo).\n */\n channels: number\n\n /**\n * The bit depth of the trimmed audio, applicable to PCM formats like `'wav'`.\n */\n bitDepth: number\n\n /**\n * The MIME type of the trimmed audio file (e.g., `'audio/wav'`, `'audio/mpeg'`).\n */\n mimeType: string\n\n /**\n * Information about compression if the output format is compressed.\n */\n compression?: {\n /**\n * The format of the compression (e.g., `'aac'`, `'mp3'`, `'opus'`).\n */\n format: string\n\n /**\n * The bitrate of the compressed audio in bits per second.\n */\n bitrate: number\n\n /**\n * The size of the compressed audio file in bytes.\n */\n size: number\n }\n\n /**\n * Information about the processing time.\n */\n processingInfo?: {\n /**\n * The time it took to process the audio in milliseconds.\n */\n durationMs: number\n }\n}\n"]}
|