@siteed/expo-audio-studio 2.12.3 → 2.13.1

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/android/build.gradle +11 -0
  3. package/android/src/main/AndroidManifest.xml +8 -0
  4. package/android/src/main/java/net/siteed/audiostream/AudioDeviceManager.kt +266 -42
  5. package/android/src/main/java/net/siteed/audiostream/ExpoAudioStreamModule.kt +55 -1
  6. package/app.plugin.js +3 -1
  7. package/build/cjs/AudioAnalysis/AudioAnalysis.types.js.map +1 -1
  8. package/build/cjs/AudioDeviceManager.js +229 -40
  9. package/build/cjs/AudioDeviceManager.js.map +1 -1
  10. package/build/cjs/WebRecorder.web.js +1 -0
  11. package/build/cjs/WebRecorder.web.js.map +1 -1
  12. package/build/cjs/hooks/useAudioDevices.js +30 -5
  13. package/build/cjs/hooks/useAudioDevices.js.map +1 -1
  14. package/build/cjs/useAudioRecorder.js +53 -8
  15. package/build/cjs/useAudioRecorder.js.map +1 -1
  16. package/build/cjs/workers/InlineFeaturesExtractor.web.js +8 -2
  17. package/build/cjs/workers/InlineFeaturesExtractor.web.js.map +1 -1
  18. package/build/esm/AudioAnalysis/AudioAnalysis.types.js.map +1 -1
  19. package/build/esm/AudioDeviceManager.js +229 -40
  20. package/build/esm/AudioDeviceManager.js.map +1 -1
  21. package/build/esm/WebRecorder.web.js +1 -0
  22. package/build/esm/WebRecorder.web.js.map +1 -1
  23. package/build/esm/hooks/useAudioDevices.js +31 -6
  24. package/build/esm/hooks/useAudioDevices.js.map +1 -1
  25. package/build/esm/useAudioRecorder.js +54 -9
  26. package/build/esm/useAudioRecorder.js.map +1 -1
  27. package/build/esm/workers/InlineFeaturesExtractor.web.js +8 -2
  28. package/build/esm/workers/InlineFeaturesExtractor.web.js.map +1 -1
  29. package/build/types/AudioAnalysis/AudioAnalysis.types.d.ts +1 -0
  30. package/build/types/AudioAnalysis/AudioAnalysis.types.d.ts.map +1 -1
  31. package/build/types/AudioDeviceManager.d.ts +82 -2
  32. package/build/types/AudioDeviceManager.d.ts.map +1 -1
  33. package/build/types/WebRecorder.web.d.ts.map +1 -1
  34. package/build/types/hooks/useAudioDevices.d.ts +1 -0
  35. package/build/types/hooks/useAudioDevices.d.ts.map +1 -1
  36. package/build/types/useAudioRecorder.d.ts.map +1 -1
  37. package/build/types/workers/InlineFeaturesExtractor.web.d.ts +1 -1
  38. package/build/types/workers/InlineFeaturesExtractor.web.d.ts.map +1 -1
  39. package/ios/AudioDeviceManager.swift +21 -9
  40. package/ios/ExpoAudioStreamModule.swift +33 -1
  41. package/package.json +7 -6
  42. package/plugin/build/index.cjs +194 -0
  43. package/plugin/build/index.d.cts +1 -0
  44. package/plugin/build/index.js +7 -6
  45. package/plugin/src/index.ts +8 -8
  46. package/src/AudioAnalysis/AudioAnalysis.types.ts +1 -0
  47. package/src/AudioDeviceManager.ts +290 -59
  48. package/src/WebRecorder.web.ts +1 -0
  49. package/src/hooks/useAudioDevices.ts +39 -6
  50. package/src/useAudioRecorder.tsx +103 -9
  51. package/src/workers/InlineFeaturesExtractor.web.tsx +8 -2
@@ -1 +1 @@
1
- {"version":3,"file":"WebRecorder.web.js","sourceRoot":"","sources":["../../src/WebRecorder.web.ts"],"names":[],"mappings":";AAAA,oDAAoD;;;AAQpD,mEAA+D;AAC/D,2DAAuD;AACvD,uFAA+E;AAC/E,iFAAyE;AAmBzE,MAAM,oBAAoB,GAAG,EAAE,CAAA;AAC/B,MAAM,2BAA2B,GAAG,GAAG,CAAA;AACvC,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAChC,MAAM,8BAA8B,GAAG,CAAC,CAAA;AAExC,MAAM,GAAG,GAAG,aAAa,CAAA;AAEzB,MAAa,WAAW;IACb,YAAY,CAAc;IACzB,gBAAgB,CAAmB;IACnC,sBAAsB,CAAS;IAC/B,MAAM,CAA4B;IAClC,sBAAsB,CAAwB;IAC9C,yBAAyB,CAA2B;IAC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,EAAE,KAAK,CACd,UAAU,MAAM,CAAC,MAAM,yCAAyC,CACnE,CAAA;YACD,IAAI,CAAC,gBAAgB,GAAG,CAAC,GAAG,MAAM,EAAE,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAA;YAC7D,cAAc;YACd,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAC9C,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,EAClC,CAAC,CACJ,CAAA;QACL,CAAC;IACL,CAAC;CACJ;AAt8BD,kCAs8BC","sourcesContent":["// packages/expo-audio-stream/src/WebRecorder.web.ts\n\nimport { AudioAnalysis } from './AudioAnalysis/AudioAnalysis.types'\nimport { ConsoleLike, RecordingConfig } from './ExpoAudioStream.types'\nimport {\n EmitAudioAnalysisFunction,\n EmitAudioEventFunction,\n} from './ExpoAudioStream.web'\nimport { encodingToBitDepth } from './utils/encodingToBitDepth'\nimport { writeWavHeader } from './utils/writeWavHeader'\nimport { InlineFeaturesExtractor } from './workers/InlineFeaturesExtractor.web'\nimport { InlineAudioWebWorker } from './workers/inlineAudioWebWorker.web'\n\ninterface AudioWorkletEvent {\n data: {\n command: string\n recordedData?: Float32Array\n sampleRate?: number\n position?: number\n message?: string // For debug messages\n }\n}\n\ninterface AudioFeaturesEvent {\n data: {\n command: string\n result: AudioAnalysis\n }\n}\n\nconst DEFAULT_WEB_BITDEPTH = 32\nconst DEFAULT_SEGMENT_DURATION_MS = 100\nconst DEFAULT_WEB_INTERVAL = 500\nconst DEFAULT_WEB_NUMBER_OF_CHANNELS = 1\n\nconst TAG = 'WebRecorder'\n\nexport class WebRecorder {\n public audioContext: AudioContext\n private audioWorkletNode!: AudioWorkletNode\n private featureExtractorWorker?: Worker\n private source: MediaStreamAudioSourceNode\n private emitAudioEventCallback: EmitAudioEventFunction\n private emitAudioAnalysisCallback: EmitAudioAnalysisFunction\n private config: RecordingConfig\n private position: number = 0\n private numberOfChannels: number // Number of audio channels\n private bitDepth: number // Bit depth of the audio\n private exportBitDepth: number // Bit depth of the audio\n private audioAnalysisData: AudioAnalysis // Keep updating the full audio analysis data with latest events\n private readonly logger?: ConsoleLike\n private compressedMediaRecorder: MediaRecorder | null = null\n private compressedChunks: Blob[] = []\n private compressedSize: number = 0\n private pendingCompressedChunk: Blob | null = null\n private dataPointIdCounter: number = 0 // Add this property to track the counter\n private deviceDisconnectionHandler: (() => void) | null = null\n private readonly mediaStream: MediaStream | null = null\n private readonly onInterruptionCallback?: (event: {\n reason: string\n isPaused: boolean\n timestamp: number\n }) => void\n private _isDeviceDisconnected: boolean = false\n private pcmData: Float32Array | null = null // Store original PCM data\n private totalSampleCount: number = 0\n\n /**\n * Flag to indicate whether this is the first audio chunk after a device switch\n * Used to maintain proper duration counting\n */\n public isFirstChunkAfterSwitch: boolean = false\n\n /**\n * Gets whether the recording device has been disconnected\n */\n get isDeviceDisconnected(): boolean {\n return this._isDeviceDisconnected\n }\n\n /**\n * Initializes a new WebRecorder instance for audio recording and processing\n * @param audioContext - The AudioContext to use for recording\n * @param source - The MediaStreamAudioSourceNode providing the audio input\n * @param recordingConfig - Configuration options for the recording\n * @param emitAudioEventCallback - Callback function for audio data events\n * @param emitAudioAnalysisCallback - Callback function for audio analysis events\n * @param onInterruption - Callback for recording interruptions\n * @param logger - Optional logger for debugging information\n */\n constructor({\n audioContext,\n source,\n recordingConfig,\n emitAudioEventCallback,\n emitAudioAnalysisCallback,\n onInterruption,\n logger,\n }: {\n audioContext: AudioContext\n source: MediaStreamAudioSourceNode\n recordingConfig: RecordingConfig\n emitAudioEventCallback: EmitAudioEventFunction\n emitAudioAnalysisCallback: EmitAudioAnalysisFunction\n onInterruption?: (event: {\n reason: string\n isPaused: boolean\n timestamp: number\n }) => void\n logger?: ConsoleLike\n }) {\n this.audioContext = audioContext\n this.source = source\n this.emitAudioEventCallback = emitAudioEventCallback\n this.emitAudioAnalysisCallback = emitAudioAnalysisCallback\n this.config = recordingConfig\n this.logger = logger\n\n const audioContextFormat = this.checkAudioContextFormat({\n sampleRate: this.audioContext.sampleRate,\n })\n this.logger?.debug('Initialized WebRecorder with config:', {\n sampleRate: audioContextFormat.sampleRate,\n bitDepth: audioContextFormat.bitDepth,\n numberOfChannels: audioContextFormat.numberOfChannels,\n })\n\n this.bitDepth = audioContextFormat.bitDepth\n this.numberOfChannels =\n audioContextFormat.numberOfChannels ||\n DEFAULT_WEB_NUMBER_OF_CHANNELS // Default to 1 if not available\n this.exportBitDepth =\n encodingToBitDepth({\n encoding: recordingConfig.encoding ?? 'pcm_32bit',\n }) ||\n audioContextFormat.bitDepth ||\n DEFAULT_WEB_BITDEPTH\n\n this.audioAnalysisData = {\n amplitudeRange: { min: 0, max: 0 },\n rmsRange: { min: 0, max: 0 },\n dataPoints: [],\n durationMs: 0,\n samples: 0,\n bitDepth: this.bitDepth,\n numberOfChannels: this.numberOfChannels,\n sampleRate: this.config.sampleRate || this.audioContext.sampleRate,\n segmentDurationMs:\n this.config.segmentDurationMs ?? DEFAULT_SEGMENT_DURATION_MS, // Default to 100ms segments\n }\n\n if (recordingConfig.enableProcessing) {\n this.initFeatureExtractorWorker()\n }\n\n // Initialize compressed recording if enabled\n if (recordingConfig.output?.compressed?.enabled) {\n this.initializeCompressedRecorder()\n }\n\n this.mediaStream = source.mediaStream\n this.onInterruptionCallback = onInterruption\n\n // Setup device disconnection detection\n this.setupDeviceDisconnectionDetection()\n }\n\n /**\n * Initializes the audio worklet using an inline script\n * Creates and connects the audio processing pipeline\n */\n async init() {\n try {\n // Create and use inline audio worklet\n const blob = new Blob([InlineAudioWebWorker], {\n type: 'application/javascript',\n })\n const url = URL.createObjectURL(blob)\n await this.audioContext.audioWorklet.addModule(url)\n\n this.audioWorkletNode = new AudioWorkletNode(\n this.audioContext,\n 'recorder-processor'\n )\n\n this.audioWorkletNode.port.onmessage = async (\n event: AudioWorkletEvent\n ) => {\n const command = event.data.command\n if (command === 'debug') {\n this.logger?.debug(`[AudioWorklet] ${event.data.message}`)\n return\n }\n\n if (command !== 'newData') return\n\n const pcmBufferFloat = event.data.recordedData\n if (!pcmBufferFloat) {\n this.logger?.warn('Received empty audio buffer', event)\n return\n }\n\n // Process data in smaller chunks and emit immediately\n const sampleRate =\n event.data.sampleRate ?? this.audioContext.sampleRate\n // Use chunk size from config interval or default to 2 seconds\n const intervalMs = this.config.interval ?? DEFAULT_WEB_INTERVAL\n const chunkSize = Math.floor(sampleRate * (intervalMs / 1000))\n const duration = pcmBufferFloat.length / sampleRate\n\n // Use incoming position if provided by worklet, otherwise use our tracked position\n const incomingPosition =\n typeof event.data.position === 'number'\n ? event.data.position\n : this.position\n\n // Simple position tracking for logging (no duplicate filtering)\n this.logger?.debug(\n `Audio chunk: position=${incomingPosition.toFixed(3)}s, size=${pcmBufferFloat.length}`\n )\n\n // Calculate bytes per sample based on bit depth\n const bytesPerSample = this.bitDepth / 8\n\n // Emit chunks without storing them\n for (let i = 0; i < pcmBufferFloat.length; i += chunkSize) {\n const chunk = pcmBufferFloat.slice(i, i + chunkSize)\n const chunkPosition = incomingPosition + i / sampleRate\n\n // Calculate byte positions and samples\n const startPosition = Math.floor(i * bytesPerSample)\n const endPosition = Math.floor(\n (i + chunk.length) * bytesPerSample\n )\n const samples = chunk.length // Number of samples in this chunk\n\n // Only store PCM data if primary output is enabled\n const shouldStoreUncompressed =\n this.config.output?.primary?.enabled ?? true\n\n // Store PCM chunks when needed - this is for the final WAV file\n if (shouldStoreUncompressed) {\n // Store the original Float32Array data for later WAV creation\n this.appendPcmData(chunk)\n this.totalSampleCount += chunk.length\n }\n\n // Process features if enabled\n if (\n this.config.enableProcessing &&\n this.featureExtractorWorker\n ) {\n this.featureExtractorWorker.postMessage({\n command: 'process',\n channelData: chunk,\n sampleRate,\n segmentDurationMs:\n this.config.segmentDurationMs ??\n DEFAULT_SEGMENT_DURATION_MS, // Default to 100ms\n bitDepth: this.bitDepth,\n fullAudioDurationMs: chunkPosition * 1000,\n numberOfChannels: this.numberOfChannels,\n features: this.config.features,\n intervalAnalysis: this.config.intervalAnalysis,\n startPosition,\n endPosition,\n samples,\n })\n }\n\n // Prepare compression data if available\n const compression = this.pendingCompressedChunk\n ? {\n data: this.pendingCompressedChunk,\n size: this.pendingCompressedChunk.size,\n totalSize: this.compressedSize,\n mimeType: 'audio/webm',\n format:\n this.config.output?.compressed?.format ??\n 'opus',\n bitrate:\n this.config.output?.compressed?.bitrate ??\n 128000,\n }\n : undefined\n\n // Emit chunk immediately - whether compressed or not\n this.emitAudioEventCallback({\n data: chunk,\n position: chunkPosition,\n compression,\n })\n\n // Reset pending compressed chunk after we've used it\n this.pendingCompressedChunk = null\n }\n\n // Update our position based on the worklet's position if provided\n this.position = incomingPosition + duration\n }\n\n // Ensure we use all relevant settings from config\n const recordSampleRate = this.audioContext.sampleRate\n const exportSampleRate =\n this.config.sampleRate ?? this.audioContext.sampleRate\n const channels = this.config.channels ?? this.numberOfChannels\n const interval = this.config.interval ?? DEFAULT_WEB_INTERVAL\n\n this.logger?.debug(`WebRecorder initialized with config:`, {\n recordSampleRate,\n exportSampleRate,\n bitDepth: this.bitDepth,\n exportBitDepth: this.exportBitDepth,\n channels,\n interval,\n position: this.position,\n deviceId: this.config.deviceId ?? 'default',\n compression: this.config.output?.compressed\n ? {\n enabled: this.config.output.compressed.enabled,\n format: this.config.output.compressed.format,\n bitrate: this.config.output.compressed.bitrate,\n }\n : 'disabled',\n })\n\n // Initialize the worklet with all settings from config\n this.audioWorkletNode.port.postMessage({\n command: 'init',\n recordSampleRate,\n exportSampleRate,\n bitDepth: this.bitDepth,\n exportBitDepth: this.exportBitDepth,\n channels,\n interval,\n position: this.position, // Pass the current position to the processor\n enableLogging: true,\n })\n\n // Connect the source to the AudioWorkletNode and start recording\n this.source.connect(this.audioWorkletNode)\n this.audioWorkletNode.connect(this.audioContext.destination)\n } catch (error) {\n console.error(`[${TAG}] Failed to initialize WebRecorder`, error)\n }\n }\n\n /**\n * Append new PCM data to the existing buffer\n * @param newData New Float32Array data to append\n */\n private appendPcmData(newData: Float32Array): void {\n // Clone the incoming data to ensure it's not modified\n const dataToAdd = new Float32Array(newData)\n\n if (!this.pcmData) {\n // First chunk - create a copy to avoid references to original data\n this.pcmData = new Float32Array(dataToAdd)\n return\n }\n\n // Create a new buffer with increased size\n const newBuffer = new Float32Array(\n this.pcmData.length + dataToAdd.length\n )\n\n // Copy existing data\n newBuffer.set(this.pcmData)\n\n // Append new data\n newBuffer.set(dataToAdd, this.pcmData.length)\n\n // Replace existing buffer\n this.pcmData = newBuffer\n }\n\n /**\n * Initializes the feature extractor worker for audio analysis\n * Creates an inline worker from a blob for audio feature extraction\n */\n initFeatureExtractorWorker() {\n try {\n const blob = new Blob([InlineFeaturesExtractor], {\n type: 'application/javascript',\n })\n const url = URL.createObjectURL(blob)\n this.featureExtractorWorker = new Worker(url)\n this.featureExtractorWorker.onmessage =\n this.handleFeatureExtractorMessage.bind(this)\n this.featureExtractorWorker.onerror = (error) => {\n console.error(`[${TAG}] Feature extractor worker error:`, error)\n }\n\n // Initialize worker with counter if needed\n if (this.dataPointIdCounter > 0) {\n this.featureExtractorWorker.postMessage({\n command: 'resetCounter',\n value: this.dataPointIdCounter,\n })\n this.logger?.debug(\n `Initialized worker with counter value ${this.dataPointIdCounter}`\n )\n }\n\n this.logger?.log(\n 'Feature extractor worker initialized successfully'\n )\n } catch (error) {\n console.error(\n `[${TAG}] Failed to initialize feature extractor worker`,\n error\n )\n }\n }\n\n /**\n * Processes audio analysis results from the feature extractor worker\n * Updates the audio analysis data and emits events\n * @param event - The event containing audio analysis results\n */\n handleFeatureExtractorMessage(event: AudioFeaturesEvent) {\n if (event.data.command !== 'features') return\n\n const segmentResult = event.data.result\n const uniqueNewDataPoints = this.filterUniqueDataPoints(\n segmentResult.dataPoints\n )\n\n // Update counter based on the highest ID seen\n this.updateDataPointCounter(uniqueNewDataPoints)\n\n // Update analysis data with the new results\n this.updateAudioAnalysisData(segmentResult, uniqueNewDataPoints)\n\n // Send filtered result to avoid duplicate IDs\n const filteredSegmentResult = {\n ...segmentResult,\n dataPoints: uniqueNewDataPoints,\n }\n\n this.emitAudioAnalysisCallback(filteredSegmentResult)\n }\n\n /**\n * Filters out data points with duplicate IDs\n */\n private filterUniqueDataPoints(dataPoints: any[]): any[] {\n // Track existing IDs to prevent duplicates\n const existingIds = new Set(\n this.audioAnalysisData.dataPoints.map((dp) => dp.id)\n )\n\n // Filter out datapoints with duplicate IDs\n const uniquePoints = dataPoints.filter((dp) => !existingIds.has(dp.id))\n\n // Log filtered duplicates if any\n if (uniquePoints.length < dataPoints.length && this.logger?.warn) {\n this.logger.warn(\n `Filtered ${dataPoints.length - uniquePoints.length} duplicate datapoints`\n )\n }\n\n return uniquePoints\n }\n\n /**\n * Updates the counter based on the highest ID in datapoints\n */\n private updateDataPointCounter(dataPoints: any[]): void {\n if (dataPoints.length === 0) return\n\n const lastDataPoint = dataPoints[dataPoints.length - 1]\n if (lastDataPoint && typeof lastDataPoint.id === 'number') {\n const nextIdValue = lastDataPoint.id + 1\n if (nextIdValue > this.dataPointIdCounter) {\n this.dataPointIdCounter = nextIdValue\n this.logger?.debug(\n `Counter updated to ${this.dataPointIdCounter}`\n )\n }\n }\n }\n\n /**\n * Updates audio analysis data with segment results\n */\n private updateAudioAnalysisData(\n segmentResult: AudioAnalysis,\n uniqueDataPoints: any[]\n ): void {\n // Add unique data points to our analysis data\n this.audioAnalysisData.dataPoints.push(...uniqueDataPoints)\n this.audioAnalysisData.durationMs += segmentResult.durationMs\n this.audioAnalysisData.sampleRate = segmentResult.sampleRate\n\n // Update amplitude range if present\n if (segmentResult.amplitudeRange) {\n this.audioAnalysisData.amplitudeRange = this.mergeRange(\n this.audioAnalysisData.amplitudeRange,\n segmentResult.amplitudeRange\n )\n }\n\n // Update RMS range if present\n if (segmentResult.rmsRange) {\n this.audioAnalysisData.rmsRange = this.mergeRange(\n this.audioAnalysisData.rmsRange,\n segmentResult.rmsRange\n )\n }\n }\n\n /**\n * Merges value ranges\n */\n private mergeRange(\n existing: { min: number; max: number } | undefined,\n newRange: { min: number; max: number }\n ): { min: number; max: number } {\n if (!existing) return { ...newRange }\n\n return {\n min: Math.min(existing.min, newRange.min),\n max: Math.max(existing.max, newRange.max),\n }\n }\n\n /**\n * Reset the data point counter to a specific value or zero\n * @param startCounterFrom Optional value to start the counter from (for continuing from previous recordings)\n */\n resetDataPointCounter(startCounterFrom?: number): void {\n // Set the counter with the passed value or 0\n this.dataPointIdCounter = startCounterFrom ?? 0\n this.logger?.debug(\n `Reset data point counter to ${this.dataPointIdCounter}`\n )\n\n // Update worker counter if available\n if (this.featureExtractorWorker) {\n this.featureExtractorWorker.postMessage({\n command: 'resetCounter',\n value: this.dataPointIdCounter,\n })\n } else {\n this.logger?.warn(\n 'No feature extractor worker available to update counter'\n )\n }\n }\n\n /**\n * Get the current data point counter value\n * @returns The current value of the data point counter\n */\n getDataPointCounter(): number {\n return this.dataPointIdCounter\n }\n\n /**\n * Prepares the recorder for continuity after device switch\n * Sets up all necessary state to maintain proper recording continuity\n */\n prepareForDeviceSwitch(): void {\n this.isFirstChunkAfterSwitch = true\n this.logger?.debug(\n `Prepared for device switch at position ${this.position}s`\n )\n }\n\n /**\n * Starts the audio recording process\n * Connects the audio nodes and begins capturing audio data\n * @param preserveCounters If true, do not reset the counter (used for device switching)\n */\n start(preserveCounters = false) {\n this.source.connect(this.audioWorkletNode)\n this.audioWorkletNode.connect(this.audioContext.destination)\n\n // Only reset the counter when not preserving state (e.g., for a fresh recording)\n if (!preserveCounters) {\n this.logger?.debug(\n 'Starting fresh recording, resetting counter to 0'\n )\n this.resetDataPointCounter(0) // Explicitly reset to 0 for new recordings\n this.isFirstChunkAfterSwitch = false\n\n // Clear PCM data for new recording\n this.pcmData = null\n this.totalSampleCount = 0\n } else {\n this.logger?.debug(\n `Preserving counter at ${this.dataPointIdCounter} during device switch`\n )\n }\n\n if (this.compressedMediaRecorder) {\n this.compressedMediaRecorder.start(this.config.interval ?? 1000)\n }\n }\n\n /**\n * Creates a WAV file from the stored PCM data\n */\n private createWavFromPcmData(): Blob | null {\n try {\n // Check if we have PCM data\n if (!this.pcmData || this.pcmData.length === 0) {\n this.logger?.warn('No PCM data available to create WAV file')\n return null\n }\n\n const sampleRate =\n this.config.sampleRate ?? this.audioContext.sampleRate\n const channels = this.numberOfChannels || 1\n\n // Convert float32 PCM data to 16-bit PCM for WAV\n const bytesPerSample = 2 // 16-bit = 2 bytes\n const dataLength = this.pcmData.length * bytesPerSample\n const buffer = new ArrayBuffer(dataLength)\n const view = new DataView(buffer)\n\n // Convert Float32Array (-1 to 1) to Int16Array (-32768 to 32767)\n for (let i = 0; i < this.pcmData.length; i++) {\n const sample = Math.max(-1, Math.min(1, this.pcmData[i]))\n const int16Value = Math.round(sample * 32767)\n view.setInt16(i * 2, int16Value, true)\n }\n\n // Use the existing writeWavHeader utility to add a WAV header\n const wavBuffer = writeWavHeader({\n buffer,\n sampleRate,\n numChannels: channels,\n bitDepth: 16,\n isFloat: false,\n })\n\n return new Blob([wavBuffer], { type: 'audio/wav' })\n } catch (error) {\n this.logger?.error('Error creating WAV file from PCM data:', error)\n return null\n }\n }\n\n /**\n * Stops the audio recording process and returns the recorded data\n * @returns Promise resolving to an object containing compressed and/or uncompressed blobs\n */\n async stop(): Promise<{ compressedBlob?: Blob; uncompressedBlob?: Blob }> {\n try {\n // Stop any compressed recording first\n if (\n this.compressedMediaRecorder &&\n this.compressedMediaRecorder.state !== 'inactive'\n ) {\n this.compressedMediaRecorder.stop()\n }\n\n // Wait for any pending compressed chunks to be processed\n if (this.compressedMediaRecorder) {\n // Small delay to ensure all data is processed\n await new Promise((resolve) => setTimeout(resolve, 100))\n }\n\n // Create uncompressed WAV file from the PCM data\n let uncompressedBlob: Blob | undefined\n\n // Only create WAV if we have PCM data\n if (this.pcmData && this.pcmData.length > 0) {\n uncompressedBlob = this.createWavFromPcmData() || undefined\n }\n\n // Return the compressed and/or uncompressed blobs if available\n return {\n compressedBlob:\n this.compressedChunks.length > 0\n ? new Blob(this.compressedChunks, {\n type: 'audio/webm;codecs=opus',\n })\n : undefined,\n uncompressedBlob,\n }\n } finally {\n this.cleanup()\n // Reset the chunks array\n this.compressedChunks = []\n this.compressedSize = 0\n this.pendingCompressedChunk = null\n this.pcmData = null\n this.totalSampleCount = 0\n this.dataPointIdCounter = 0 // Reset counter\n }\n }\n\n /**\n * Cleans up resources when recording is stopped\n * Closes audio context and disconnects nodes\n */\n public cleanup() {\n // Remove device disconnection handler\n if (this.deviceDisconnectionHandler) {\n this.deviceDisconnectionHandler()\n this.deviceDisconnectionHandler = null\n }\n\n // Check if AudioContext is already closed before attempting to close it\n if (this.audioContext && this.audioContext.state !== 'closed') {\n this.audioContext.close().catch((e) => {\n // Log closure errors but continue cleanup\n this.logger?.warn('Error closing AudioContext:', e)\n })\n }\n\n // Safely disconnect audioWorkletNode if it exists\n if (this.audioWorkletNode) {\n try {\n this.audioWorkletNode.disconnect()\n } catch (e) {\n // Log disconnection errors but continue cleanup\n this.logger?.warn('Error disconnecting audioWorkletNode:', e)\n }\n }\n\n // Safely disconnect source if it exists\n if (this.source) {\n try {\n this.source.disconnect()\n } catch (e) {\n // Log disconnection errors but continue cleanup\n this.logger?.warn('Error disconnecting source:', e)\n }\n }\n\n // Always stop media stream tracks to release hardware resources\n this.stopMediaStreamTracks()\n\n // Mark as disconnected to prevent future errors\n this._isDeviceDisconnected = true\n }\n\n /**\n * Pauses the audio recording process\n * Disconnects audio nodes and pauses the media recorder\n */\n pause() {\n try {\n // Note: We're just pausing, not disconnecting the device\n // Simply disconnect nodes temporarily without marking device as disconnected\n this.source.disconnect(this.audioWorkletNode)\n this.audioWorkletNode.disconnect(this.audioContext.destination)\n this.audioWorkletNode.port.postMessage({ command: 'pause' })\n\n if (this.compressedMediaRecorder?.state === 'recording') {\n this.compressedMediaRecorder.pause()\n }\n\n this.logger?.debug('Recording paused successfully')\n } catch (error) {\n this.logger?.error('Error in pause(): ', error)\n // Already disconnected, just ignore and continue\n }\n }\n\n /**\n * Stops all media stream tracks to release hardware resources\n * Ensures recording indicators (like microphone icon) are turned off\n */\n public stopMediaStreamTracks() {\n // Stop all audio tracks to stop the recording icon\n if (this.mediaStream) {\n const tracks = this.mediaStream.getTracks()\n tracks.forEach((track) => track.stop())\n } else if (this.source?.mediaStream) {\n const tracks = this.source.mediaStream.getTracks()\n tracks.forEach((track) => track.stop())\n }\n }\n\n /**\n * Determines the audio format capabilities of the current audio context\n * @param sampleRate - The sample rate to check\n * @returns Object containing format information (sample rate, bit depth, channels)\n */\n private checkAudioContextFormat({ sampleRate }: { sampleRate: number }) {\n // Create a silent AudioBuffer\n const frameCount = sampleRate * 1.0 // 1 second buffer\n const audioBuffer = this.audioContext.createBuffer(\n 1,\n frameCount,\n sampleRate\n )\n\n // Check the format\n const channelData = audioBuffer.getChannelData(0)\n const bitDepth = channelData.BYTES_PER_ELEMENT * 8 // 4 bytes per element means 32-bit\n\n return {\n sampleRate: audioBuffer.sampleRate,\n bitDepth,\n numberOfChannels: audioBuffer.numberOfChannels,\n }\n }\n\n /**\n * Resumes a paused recording\n * Reconnects audio nodes and resumes the media recorder\n */\n resume() {\n // If device was disconnected, we can't resume\n if (this._isDeviceDisconnected) {\n this.logger?.warn('Cannot resume recording: device disconnected')\n return\n }\n\n try {\n this.source.connect(this.audioWorkletNode)\n this.audioWorkletNode.connect(this.audioContext.destination)\n this.audioWorkletNode.port.postMessage({ command: 'resume' })\n this.compressedMediaRecorder?.resume()\n } catch (error: unknown) {\n this.logger?.error('Error in resume(): ', error)\n // Rethrow the error to inform callers\n throw new Error(\n `Failed to resume recording: ${error instanceof Error ? error.message : 'unknown error'}`\n )\n }\n }\n\n /**\n * Initializes the compressed media recorder if compression is enabled\n * Sets up event handlers for compressed audio data\n */\n private initializeCompressedRecorder() {\n try {\n const mimeType = 'audio/webm;codecs=opus'\n if (!MediaRecorder.isTypeSupported(mimeType)) {\n this.logger?.warn(\n 'Opus compression not supported in this browser'\n )\n return\n }\n\n this.compressedMediaRecorder = new MediaRecorder(\n this.source.mediaStream,\n {\n mimeType,\n audioBitsPerSecond:\n this.config.output?.compressed?.bitrate ?? 128000,\n }\n )\n\n this.compressedMediaRecorder.ondataavailable = (event) => {\n if (event.data.size > 0) {\n // Store the compressed chunk for final blob creation\n this.compressedChunks.push(event.data)\n this.compressedSize += event.data.size\n\n // Store the pending compressed chunk for the next PCM chunk to use\n this.pendingCompressedChunk = event.data\n }\n }\n } catch (error) {\n this.logger?.error(\n 'Failed to initialize compressed recorder:',\n error\n )\n // Setting to null to indicate initialization failed\n this.compressedMediaRecorder = null\n }\n }\n\n /**\n * Processes features if enabled\n */\n processFeatures(\n chunk: Float32Array,\n sampleRate: number,\n chunkPosition: number,\n startPosition: number,\n endPosition: number,\n samples: number\n ) {\n if (this.config.enableProcessing && this.featureExtractorWorker) {\n this.featureExtractorWorker.postMessage({\n command: 'process',\n channelData: chunk,\n sampleRate,\n segmentDurationMs:\n this.config.segmentDurationMs ??\n DEFAULT_SEGMENT_DURATION_MS, // Default to 100ms\n bitDepth: this.bitDepth,\n fullAudioDurationMs: chunkPosition * 1000,\n numberOfChannels: this.numberOfChannels,\n features: this.config.features,\n intervalAnalysis: this.config.intervalAnalysis,\n startPosition,\n endPosition,\n samples,\n })\n }\n }\n\n /**\n * Sets up detection for device disconnection events\n */\n private setupDeviceDisconnectionDetection() {\n if (!this.mediaStream) return\n\n // Function to handle track ending (which happens on device disconnection)\n const handleTrackEnded = () => {\n this.logger?.warn('Audio track ended - device disconnected')\n this._isDeviceDisconnected = true\n\n // Use the callback to notify parent component about device disconnection\n if (this.onInterruptionCallback) {\n this.onInterruptionCallback({\n reason: 'deviceDisconnected',\n isPaused: true,\n timestamp: Date.now(),\n })\n this.logger?.debug('Notified about device disconnection')\n }\n\n // Ensure we disconnect nodes to prevent zombie recordings\n if (this.audioWorkletNode) {\n this.audioWorkletNode.port.postMessage({\n command: 'deviceDisconnected',\n })\n\n try {\n this.source.disconnect(this.audioWorkletNode)\n this.audioWorkletNode.disconnect()\n } catch (e) {\n // Ignore disconnection errors as the track might already be gone\n this.logger?.warn(\n 'Error disconnecting audioWorkletNode:',\n e\n )\n }\n }\n }\n\n // Add listeners to all audio tracks\n const tracks = this.mediaStream.getAudioTracks()\n tracks.forEach((track) => {\n track.addEventListener('ended', handleTrackEnded)\n })\n\n // Store the handler for cleanup\n this.deviceDisconnectionHandler = () => {\n tracks.forEach((track) => {\n track.removeEventListener('ended', handleTrackEnded)\n })\n }\n }\n\n /**\n * Explicitly set the position for continuous recording across device switches\n * @param position The position in seconds to continue from\n */\n setPosition(position: number): void {\n if (position >= 0) {\n this.position = position\n this.logger?.debug(`Position explicitly set to ${position} seconds`)\n } else {\n this.logger?.warn(`Invalid position value: ${position}, ignoring`)\n }\n }\n\n /**\n * Get the current position in seconds\n * @returns The current position\n */\n getPosition(): number {\n return this.position\n }\n\n /**\n * Gets the current compressed chunks\n * @returns Array of current compressed audio chunks\n */\n getCompressedChunks(): Blob[] {\n return [...this.compressedChunks]\n }\n\n /**\n * Sets the compressed chunks from a previous recorder\n * @param chunks Array of compressed chunks from a previous recorder\n */\n setCompressedChunks(chunks: Blob[]): void {\n if (chunks && chunks.length > 0) {\n this.logger?.debug(\n `Adding ${chunks.length} compressed chunks from previous device`\n )\n this.compressedChunks = [...chunks, ...this.compressedChunks]\n // Update size\n this.compressedSize = this.compressedChunks.reduce(\n (size, chunk) => size + chunk.size,\n 0\n )\n }\n }\n}\n"]}
1
+ {"version":3,"file":"WebRecorder.web.js","sourceRoot":"","sources":["../../src/WebRecorder.web.ts"],"names":[],"mappings":";AAAA,oDAAoD;;;AAQpD,mEAA+D;AAC/D,2DAAuD;AACvD,uFAA+E;AAC/E,iFAAyE;AAmBzE,MAAM,oBAAoB,GAAG,EAAE,CAAA;AAC/B,MAAM,2BAA2B,GAAG,GAAG,CAAA;AACvC,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAChC,MAAM,8BAA8B,GAAG,CAAC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OAGG;IACH,mBAAmB;QACf,OAAO,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAA;IACrC,CAAC;IAED;;;OAGG;IACH,mBAAmB,CAAC,MAAc;QAC9B,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,EAAE,KAAK,CACd,UAAU,MAAM,CAAC,MAAM,yCAAyC,CACnE,CAAA;YACD,IAAI,CAAC,gBAAgB,GAAG,CAAC,GAAG,MAAM,EAAE,GAAG,IAAI,CAAC,gBAAgB,CAAC,CAAA;YAC7D,cAAc;YACd,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAC9C,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,EAClC,CAAC,CACJ,CAAA;QACL,CAAC;IACL,CAAC;CACJ;AAv8BD,kCAu8BC","sourcesContent":["// packages/expo-audio-stream/src/WebRecorder.web.ts\n\nimport { AudioAnalysis } from './AudioAnalysis/AudioAnalysis.types'\nimport { ConsoleLike, RecordingConfig } from './ExpoAudioStream.types'\nimport {\n EmitAudioAnalysisFunction,\n EmitAudioEventFunction,\n} from './ExpoAudioStream.web'\nimport { encodingToBitDepth } from './utils/encodingToBitDepth'\nimport { writeWavHeader } from './utils/writeWavHeader'\nimport { InlineFeaturesExtractor } from './workers/InlineFeaturesExtractor.web'\nimport { InlineAudioWebWorker } from './workers/inlineAudioWebWorker.web'\n\ninterface AudioWorkletEvent {\n data: {\n command: string\n recordedData?: Float32Array\n sampleRate?: number\n position?: number\n message?: string // For debug messages\n }\n}\n\ninterface AudioFeaturesEvent {\n data: {\n command: string\n result: AudioAnalysis\n }\n}\n\nconst DEFAULT_WEB_BITDEPTH = 32\nconst DEFAULT_SEGMENT_DURATION_MS = 100\nconst DEFAULT_WEB_INTERVAL = 500\nconst DEFAULT_WEB_NUMBER_OF_CHANNELS = 1\n\nconst TAG = 'WebRecorder'\n\nexport class WebRecorder {\n public audioContext: AudioContext\n private audioWorkletNode!: AudioWorkletNode\n private featureExtractorWorker?: Worker\n private source: MediaStreamAudioSourceNode\n private emitAudioEventCallback: EmitAudioEventFunction\n private emitAudioAnalysisCallback: EmitAudioAnalysisFunction\n private config: RecordingConfig\n private position: number = 0\n private numberOfChannels: number // Number of audio channels\n private bitDepth: number // Bit depth of the audio\n private exportBitDepth: number // Bit depth of the audio\n private audioAnalysisData: AudioAnalysis // Keep updating the full audio analysis data with latest events\n private readonly logger?: ConsoleLike\n private compressedMediaRecorder: MediaRecorder | null = null\n private compressedChunks: Blob[] = []\n private compressedSize: number = 0\n private pendingCompressedChunk: Blob | null = null\n private dataPointIdCounter: number = 0 // Add this property to track the counter\n private deviceDisconnectionHandler: (() => void) | null = null\n private readonly mediaStream: MediaStream | null = null\n private readonly onInterruptionCallback?: (event: {\n reason: string\n isPaused: boolean\n timestamp: number\n }) => void\n private _isDeviceDisconnected: boolean = false\n private pcmData: Float32Array | null = null // Store original PCM data\n private totalSampleCount: number = 0\n\n /**\n * Flag to indicate whether this is the first audio chunk after a device switch\n * Used to maintain proper duration counting\n */\n public isFirstChunkAfterSwitch: boolean = false\n\n /**\n * Gets whether the recording device has been disconnected\n */\n get isDeviceDisconnected(): boolean {\n return this._isDeviceDisconnected\n }\n\n /**\n * Initializes a new WebRecorder instance for audio recording and processing\n * @param audioContext - The AudioContext to use for recording\n * @param source - The MediaStreamAudioSourceNode providing the audio input\n * @param recordingConfig - Configuration options for the recording\n * @param emitAudioEventCallback - Callback function for audio data events\n * @param emitAudioAnalysisCallback - Callback function for audio analysis events\n * @param onInterruption - Callback for recording interruptions\n * @param logger - Optional logger for debugging information\n */\n constructor({\n audioContext,\n source,\n recordingConfig,\n emitAudioEventCallback,\n emitAudioAnalysisCallback,\n onInterruption,\n logger,\n }: {\n audioContext: AudioContext\n source: MediaStreamAudioSourceNode\n recordingConfig: RecordingConfig\n emitAudioEventCallback: EmitAudioEventFunction\n emitAudioAnalysisCallback: EmitAudioAnalysisFunction\n onInterruption?: (event: {\n reason: string\n isPaused: boolean\n timestamp: number\n }) => void\n logger?: ConsoleLike\n }) {\n this.audioContext = audioContext\n this.source = source\n this.emitAudioEventCallback = emitAudioEventCallback\n this.emitAudioAnalysisCallback = emitAudioAnalysisCallback\n this.config = recordingConfig\n this.logger = logger\n\n const audioContextFormat = this.checkAudioContextFormat({\n sampleRate: this.audioContext.sampleRate,\n })\n this.logger?.debug('Initialized WebRecorder with config:', {\n sampleRate: audioContextFormat.sampleRate,\n bitDepth: audioContextFormat.bitDepth,\n numberOfChannels: audioContextFormat.numberOfChannels,\n })\n\n this.bitDepth = audioContextFormat.bitDepth\n this.numberOfChannels =\n audioContextFormat.numberOfChannels ||\n DEFAULT_WEB_NUMBER_OF_CHANNELS // Default to 1 if not available\n this.exportBitDepth =\n encodingToBitDepth({\n encoding: recordingConfig.encoding ?? 'pcm_32bit',\n }) ||\n audioContextFormat.bitDepth ||\n DEFAULT_WEB_BITDEPTH\n\n this.audioAnalysisData = {\n amplitudeRange: { min: 0, max: 0 },\n rmsRange: { min: 0, max: 0 },\n dataPoints: [],\n durationMs: 0,\n samples: 0,\n bitDepth: this.bitDepth,\n numberOfChannels: this.numberOfChannels,\n sampleRate: this.config.sampleRate || this.audioContext.sampleRate,\n segmentDurationMs:\n this.config.segmentDurationMs ?? DEFAULT_SEGMENT_DURATION_MS, // Default to 100ms segments\n extractionTimeMs: 0,\n }\n\n if (recordingConfig.enableProcessing) {\n this.initFeatureExtractorWorker()\n }\n\n // Initialize compressed recording if enabled\n if (recordingConfig.output?.compressed?.enabled) {\n this.initializeCompressedRecorder()\n }\n\n this.mediaStream = source.mediaStream\n this.onInterruptionCallback = onInterruption\n\n // Setup device disconnection detection\n this.setupDeviceDisconnectionDetection()\n }\n\n /**\n * Initializes the audio worklet using an inline script\n * Creates and connects the audio processing pipeline\n */\n async init() {\n try {\n // Create and use inline audio worklet\n const blob = new Blob([InlineAudioWebWorker], {\n type: 'application/javascript',\n })\n const url = URL.createObjectURL(blob)\n await this.audioContext.audioWorklet.addModule(url)\n\n this.audioWorkletNode = new AudioWorkletNode(\n this.audioContext,\n 'recorder-processor'\n )\n\n this.audioWorkletNode.port.onmessage = async (\n event: AudioWorkletEvent\n ) => {\n const command = event.data.command\n if (command === 'debug') {\n this.logger?.debug(`[AudioWorklet] ${event.data.message}`)\n return\n }\n\n if (command !== 'newData') return\n\n const pcmBufferFloat = event.data.recordedData\n if (!pcmBufferFloat) {\n this.logger?.warn('Received empty audio buffer', event)\n return\n }\n\n // Process data in smaller chunks and emit immediately\n const sampleRate =\n event.data.sampleRate ?? this.audioContext.sampleRate\n // Use chunk size from config interval or default to 2 seconds\n const intervalMs = this.config.interval ?? DEFAULT_WEB_INTERVAL\n const chunkSize = Math.floor(sampleRate * (intervalMs / 1000))\n const duration = pcmBufferFloat.length / sampleRate\n\n // Use incoming position if provided by worklet, otherwise use our tracked position\n const incomingPosition =\n typeof event.data.position === 'number'\n ? event.data.position\n : this.position\n\n // Simple position tracking for logging (no duplicate filtering)\n this.logger?.debug(\n `Audio chunk: position=${incomingPosition.toFixed(3)}s, size=${pcmBufferFloat.length}`\n )\n\n // Calculate bytes per sample based on bit depth\n const bytesPerSample = this.bitDepth / 8\n\n // Emit chunks without storing them\n for (let i = 0; i < pcmBufferFloat.length; i += chunkSize) {\n const chunk = pcmBufferFloat.slice(i, i + chunkSize)\n const chunkPosition = incomingPosition + i / sampleRate\n\n // Calculate byte positions and samples\n const startPosition = Math.floor(i * bytesPerSample)\n const endPosition = Math.floor(\n (i + chunk.length) * bytesPerSample\n )\n const samples = chunk.length // Number of samples in this chunk\n\n // Only store PCM data if primary output is enabled\n const shouldStoreUncompressed =\n this.config.output?.primary?.enabled ?? true\n\n // Store PCM chunks when needed - this is for the final WAV file\n if (shouldStoreUncompressed) {\n // Store the original Float32Array data for later WAV creation\n this.appendPcmData(chunk)\n this.totalSampleCount += chunk.length\n }\n\n // Process features if enabled\n if (\n this.config.enableProcessing &&\n this.featureExtractorWorker\n ) {\n this.featureExtractorWorker.postMessage({\n command: 'process',\n channelData: chunk,\n sampleRate,\n segmentDurationMs:\n this.config.segmentDurationMs ??\n DEFAULT_SEGMENT_DURATION_MS, // Default to 100ms\n bitDepth: this.bitDepth,\n fullAudioDurationMs: chunkPosition * 1000,\n numberOfChannels: this.numberOfChannels,\n features: this.config.features,\n intervalAnalysis: this.config.intervalAnalysis,\n startPosition,\n endPosition,\n samples,\n })\n }\n\n // Prepare compression data if available\n const compression = this.pendingCompressedChunk\n ? {\n data: this.pendingCompressedChunk,\n size: this.pendingCompressedChunk.size,\n totalSize: this.compressedSize,\n mimeType: 'audio/webm',\n format:\n this.config.output?.compressed?.format ??\n 'opus',\n bitrate:\n this.config.output?.compressed?.bitrate ??\n 128000,\n }\n : undefined\n\n // Emit chunk immediately - whether compressed or not\n this.emitAudioEventCallback({\n data: chunk,\n position: chunkPosition,\n compression,\n })\n\n // Reset pending compressed chunk after we've used it\n this.pendingCompressedChunk = null\n }\n\n // Update our position based on the worklet's position if provided\n this.position = incomingPosition + duration\n }\n\n // Ensure we use all relevant settings from config\n const recordSampleRate = this.audioContext.sampleRate\n const exportSampleRate =\n this.config.sampleRate ?? this.audioContext.sampleRate\n const channels = this.config.channels ?? this.numberOfChannels\n const interval = this.config.interval ?? DEFAULT_WEB_INTERVAL\n\n this.logger?.debug(`WebRecorder initialized with config:`, {\n recordSampleRate,\n exportSampleRate,\n bitDepth: this.bitDepth,\n exportBitDepth: this.exportBitDepth,\n channels,\n interval,\n position: this.position,\n deviceId: this.config.deviceId ?? 'default',\n compression: this.config.output?.compressed\n ? {\n enabled: this.config.output.compressed.enabled,\n format: this.config.output.compressed.format,\n bitrate: this.config.output.compressed.bitrate,\n }\n : 'disabled',\n })\n\n // Initialize the worklet with all settings from config\n this.audioWorkletNode.port.postMessage({\n command: 'init',\n recordSampleRate,\n exportSampleRate,\n bitDepth: this.bitDepth,\n exportBitDepth: this.exportBitDepth,\n channels,\n interval,\n position: this.position, // Pass the current position to the processor\n enableLogging: true,\n })\n\n // Connect the source to the AudioWorkletNode and start recording\n this.source.connect(this.audioWorkletNode)\n this.audioWorkletNode.connect(this.audioContext.destination)\n } catch (error) {\n console.error(`[${TAG}] Failed to initialize WebRecorder`, error)\n }\n }\n\n /**\n * Append new PCM data to the existing buffer\n * @param newData New Float32Array data to append\n */\n private appendPcmData(newData: Float32Array): void {\n // Clone the incoming data to ensure it's not modified\n const dataToAdd = new Float32Array(newData)\n\n if (!this.pcmData) {\n // First chunk - create a copy to avoid references to original data\n this.pcmData = new Float32Array(dataToAdd)\n return\n }\n\n // Create a new buffer with increased size\n const newBuffer = new Float32Array(\n this.pcmData.length + dataToAdd.length\n )\n\n // Copy existing data\n newBuffer.set(this.pcmData)\n\n // Append new data\n newBuffer.set(dataToAdd, this.pcmData.length)\n\n // Replace existing buffer\n this.pcmData = newBuffer\n }\n\n /**\n * Initializes the feature extractor worker for audio analysis\n * Creates an inline worker from a blob for audio feature extraction\n */\n initFeatureExtractorWorker() {\n try {\n const blob = new Blob([InlineFeaturesExtractor], {\n type: 'application/javascript',\n })\n const url = URL.createObjectURL(blob)\n this.featureExtractorWorker = new Worker(url)\n this.featureExtractorWorker.onmessage =\n this.handleFeatureExtractorMessage.bind(this)\n this.featureExtractorWorker.onerror = (error) => {\n console.error(`[${TAG}] Feature extractor worker error:`, error)\n }\n\n // Initialize worker with counter if needed\n if (this.dataPointIdCounter > 0) {\n this.featureExtractorWorker.postMessage({\n command: 'resetCounter',\n value: this.dataPointIdCounter,\n })\n this.logger?.debug(\n `Initialized worker with counter value ${this.dataPointIdCounter}`\n )\n }\n\n this.logger?.log(\n 'Feature extractor worker initialized successfully'\n )\n } catch (error) {\n console.error(\n `[${TAG}] Failed to initialize feature extractor worker`,\n error\n )\n }\n }\n\n /**\n * Processes audio analysis results from the feature extractor worker\n * Updates the audio analysis data and emits events\n * @param event - The event containing audio analysis results\n */\n handleFeatureExtractorMessage(event: AudioFeaturesEvent) {\n if (event.data.command !== 'features') return\n\n const segmentResult = event.data.result\n const uniqueNewDataPoints = this.filterUniqueDataPoints(\n segmentResult.dataPoints\n )\n\n // Update counter based on the highest ID seen\n this.updateDataPointCounter(uniqueNewDataPoints)\n\n // Update analysis data with the new results\n this.updateAudioAnalysisData(segmentResult, uniqueNewDataPoints)\n\n // Send filtered result to avoid duplicate IDs\n const filteredSegmentResult = {\n ...segmentResult,\n dataPoints: uniqueNewDataPoints,\n }\n\n this.emitAudioAnalysisCallback(filteredSegmentResult)\n }\n\n /**\n * Filters out data points with duplicate IDs\n */\n private filterUniqueDataPoints(dataPoints: any[]): any[] {\n // Track existing IDs to prevent duplicates\n const existingIds = new Set(\n this.audioAnalysisData.dataPoints.map((dp) => dp.id)\n )\n\n // Filter out datapoints with duplicate IDs\n const uniquePoints = dataPoints.filter((dp) => !existingIds.has(dp.id))\n\n // Log filtered duplicates if any\n if (uniquePoints.length < dataPoints.length && this.logger?.warn) {\n this.logger.warn(\n `Filtered ${dataPoints.length - uniquePoints.length} duplicate datapoints`\n )\n }\n\n return uniquePoints\n }\n\n /**\n * Updates the counter based on the highest ID in datapoints\n */\n private updateDataPointCounter(dataPoints: any[]): void {\n if (dataPoints.length === 0) return\n\n const lastDataPoint = dataPoints[dataPoints.length - 1]\n if (lastDataPoint && typeof lastDataPoint.id === 'number') {\n const nextIdValue = lastDataPoint.id + 1\n if (nextIdValue > this.dataPointIdCounter) {\n this.dataPointIdCounter = nextIdValue\n this.logger?.debug(\n `Counter updated to ${this.dataPointIdCounter}`\n )\n }\n }\n }\n\n /**\n * Updates audio analysis data with segment results\n */\n private updateAudioAnalysisData(\n segmentResult: AudioAnalysis,\n uniqueDataPoints: any[]\n ): void {\n // Add unique data points to our analysis data\n this.audioAnalysisData.dataPoints.push(...uniqueDataPoints)\n this.audioAnalysisData.durationMs += segmentResult.durationMs\n this.audioAnalysisData.sampleRate = segmentResult.sampleRate\n\n // Update amplitude range if present\n if (segmentResult.amplitudeRange) {\n this.audioAnalysisData.amplitudeRange = this.mergeRange(\n this.audioAnalysisData.amplitudeRange,\n segmentResult.amplitudeRange\n )\n }\n\n // Update RMS range if present\n if (segmentResult.rmsRange) {\n this.audioAnalysisData.rmsRange = this.mergeRange(\n this.audioAnalysisData.rmsRange,\n segmentResult.rmsRange\n )\n }\n }\n\n /**\n * Merges value ranges\n */\n private mergeRange(\n existing: { min: number; max: number } | undefined,\n newRange: { min: number; max: number }\n ): { min: number; max: number } {\n if (!existing) return { ...newRange }\n\n return {\n min: Math.min(existing.min, newRange.min),\n max: Math.max(existing.max, newRange.max),\n }\n }\n\n /**\n * Reset the data point counter to a specific value or zero\n * @param startCounterFrom Optional value to start the counter from (for continuing from previous recordings)\n */\n resetDataPointCounter(startCounterFrom?: number): void {\n // Set the counter with the passed value or 0\n this.dataPointIdCounter = startCounterFrom ?? 0\n this.logger?.debug(\n `Reset data point counter to ${this.dataPointIdCounter}`\n )\n\n // Update worker counter if available\n if (this.featureExtractorWorker) {\n this.featureExtractorWorker.postMessage({\n command: 'resetCounter',\n value: this.dataPointIdCounter,\n })\n } else {\n this.logger?.warn(\n 'No feature extractor worker available to update counter'\n )\n }\n }\n\n /**\n * Get the current data point counter value\n * @returns The current value of the data point counter\n */\n getDataPointCounter(): number {\n return this.dataPointIdCounter\n }\n\n /**\n * Prepares the recorder for continuity after device switch\n * Sets up all necessary state to maintain proper recording continuity\n */\n prepareForDeviceSwitch(): void {\n this.isFirstChunkAfterSwitch = true\n this.logger?.debug(\n `Prepared for device switch at position ${this.position}s`\n )\n }\n\n /**\n * Starts the audio recording process\n * Connects the audio nodes and begins capturing audio data\n * @param preserveCounters If true, do not reset the counter (used for device switching)\n */\n start(preserveCounters = false) {\n this.source.connect(this.audioWorkletNode)\n this.audioWorkletNode.connect(this.audioContext.destination)\n\n // Only reset the counter when not preserving state (e.g., for a fresh recording)\n if (!preserveCounters) {\n this.logger?.debug(\n 'Starting fresh recording, resetting counter to 0'\n )\n this.resetDataPointCounter(0) // Explicitly reset to 0 for new recordings\n this.isFirstChunkAfterSwitch = false\n\n // Clear PCM data for new recording\n this.pcmData = null\n this.totalSampleCount = 0\n } else {\n this.logger?.debug(\n `Preserving counter at ${this.dataPointIdCounter} during device switch`\n )\n }\n\n if (this.compressedMediaRecorder) {\n this.compressedMediaRecorder.start(this.config.interval ?? 1000)\n }\n }\n\n /**\n * Creates a WAV file from the stored PCM data\n */\n private createWavFromPcmData(): Blob | null {\n try {\n // Check if we have PCM data\n if (!this.pcmData || this.pcmData.length === 0) {\n this.logger?.warn('No PCM data available to create WAV file')\n return null\n }\n\n const sampleRate =\n this.config.sampleRate ?? this.audioContext.sampleRate\n const channels = this.numberOfChannels || 1\n\n // Convert float32 PCM data to 16-bit PCM for WAV\n const bytesPerSample = 2 // 16-bit = 2 bytes\n const dataLength = this.pcmData.length * bytesPerSample\n const buffer = new ArrayBuffer(dataLength)\n const view = new DataView(buffer)\n\n // Convert Float32Array (-1 to 1) to Int16Array (-32768 to 32767)\n for (let i = 0; i < this.pcmData.length; i++) {\n const sample = Math.max(-1, Math.min(1, this.pcmData[i]))\n const int16Value = Math.round(sample * 32767)\n view.setInt16(i * 2, int16Value, true)\n }\n\n // Use the existing writeWavHeader utility to add a WAV header\n const wavBuffer = writeWavHeader({\n buffer,\n sampleRate,\n numChannels: channels,\n bitDepth: 16,\n isFloat: false,\n })\n\n return new Blob([wavBuffer], { type: 'audio/wav' })\n } catch (error) {\n this.logger?.error('Error creating WAV file from PCM data:', error)\n return null\n }\n }\n\n /**\n * Stops the audio recording process and returns the recorded data\n * @returns Promise resolving to an object containing compressed and/or uncompressed blobs\n */\n async stop(): Promise<{ compressedBlob?: Blob; uncompressedBlob?: Blob }> {\n try {\n // Stop any compressed recording first\n if (\n this.compressedMediaRecorder &&\n this.compressedMediaRecorder.state !== 'inactive'\n ) {\n this.compressedMediaRecorder.stop()\n }\n\n // Wait for any pending compressed chunks to be processed\n if (this.compressedMediaRecorder) {\n // Small delay to ensure all data is processed\n await new Promise((resolve) => setTimeout(resolve, 100))\n }\n\n // Create uncompressed WAV file from the PCM data\n let uncompressedBlob: Blob | undefined\n\n // Only create WAV if we have PCM data\n if (this.pcmData && this.pcmData.length > 0) {\n uncompressedBlob = this.createWavFromPcmData() || undefined\n }\n\n // Return the compressed and/or uncompressed blobs if available\n return {\n compressedBlob:\n this.compressedChunks.length > 0\n ? new Blob(this.compressedChunks, {\n type: 'audio/webm;codecs=opus',\n })\n : undefined,\n uncompressedBlob,\n }\n } finally {\n this.cleanup()\n // Reset the chunks array\n this.compressedChunks = []\n this.compressedSize = 0\n this.pendingCompressedChunk = null\n this.pcmData = null\n this.totalSampleCount = 0\n this.dataPointIdCounter = 0 // Reset counter\n }\n }\n\n /**\n * Cleans up resources when recording is stopped\n * Closes audio context and disconnects nodes\n */\n public cleanup() {\n // Remove device disconnection handler\n if (this.deviceDisconnectionHandler) {\n this.deviceDisconnectionHandler()\n this.deviceDisconnectionHandler = null\n }\n\n // Check if AudioContext is already closed before attempting to close it\n if (this.audioContext && this.audioContext.state !== 'closed') {\n this.audioContext.close().catch((e) => {\n // Log closure errors but continue cleanup\n this.logger?.warn('Error closing AudioContext:', e)\n })\n }\n\n // Safely disconnect audioWorkletNode if it exists\n if (this.audioWorkletNode) {\n try {\n this.audioWorkletNode.disconnect()\n } catch (e) {\n // Log disconnection errors but continue cleanup\n this.logger?.warn('Error disconnecting audioWorkletNode:', e)\n }\n }\n\n // Safely disconnect source if it exists\n if (this.source) {\n try {\n this.source.disconnect()\n } catch (e) {\n // Log disconnection errors but continue cleanup\n this.logger?.warn('Error disconnecting source:', e)\n }\n }\n\n // Always stop media stream tracks to release hardware resources\n this.stopMediaStreamTracks()\n\n // Mark as disconnected to prevent future errors\n this._isDeviceDisconnected = true\n }\n\n /**\n * Pauses the audio recording process\n * Disconnects audio nodes and pauses the media recorder\n */\n pause() {\n try {\n // Note: We're just pausing, not disconnecting the device\n // Simply disconnect nodes temporarily without marking device as disconnected\n this.source.disconnect(this.audioWorkletNode)\n this.audioWorkletNode.disconnect(this.audioContext.destination)\n this.audioWorkletNode.port.postMessage({ command: 'pause' })\n\n if (this.compressedMediaRecorder?.state === 'recording') {\n this.compressedMediaRecorder.pause()\n }\n\n this.logger?.debug('Recording paused successfully')\n } catch (error) {\n this.logger?.error('Error in pause(): ', error)\n // Already disconnected, just ignore and continue\n }\n }\n\n /**\n * Stops all media stream tracks to release hardware resources\n * Ensures recording indicators (like microphone icon) are turned off\n */\n public stopMediaStreamTracks() {\n // Stop all audio tracks to stop the recording icon\n if (this.mediaStream) {\n const tracks = this.mediaStream.getTracks()\n tracks.forEach((track) => track.stop())\n } else if (this.source?.mediaStream) {\n const tracks = this.source.mediaStream.getTracks()\n tracks.forEach((track) => track.stop())\n }\n }\n\n /**\n * Determines the audio format capabilities of the current audio context\n * @param sampleRate - The sample rate to check\n * @returns Object containing format information (sample rate, bit depth, channels)\n */\n private checkAudioContextFormat({ sampleRate }: { sampleRate: number }) {\n // Create a silent AudioBuffer\n const frameCount = sampleRate * 1.0 // 1 second buffer\n const audioBuffer = this.audioContext.createBuffer(\n 1,\n frameCount,\n sampleRate\n )\n\n // Check the format\n const channelData = audioBuffer.getChannelData(0)\n const bitDepth = channelData.BYTES_PER_ELEMENT * 8 // 4 bytes per element means 32-bit\n\n return {\n sampleRate: audioBuffer.sampleRate,\n bitDepth,\n numberOfChannels: audioBuffer.numberOfChannels,\n }\n }\n\n /**\n * Resumes a paused recording\n * Reconnects audio nodes and resumes the media recorder\n */\n resume() {\n // If device was disconnected, we can't resume\n if (this._isDeviceDisconnected) {\n this.logger?.warn('Cannot resume recording: device disconnected')\n return\n }\n\n try {\n this.source.connect(this.audioWorkletNode)\n this.audioWorkletNode.connect(this.audioContext.destination)\n this.audioWorkletNode.port.postMessage({ command: 'resume' })\n this.compressedMediaRecorder?.resume()\n } catch (error: unknown) {\n this.logger?.error('Error in resume(): ', error)\n // Rethrow the error to inform callers\n throw new Error(\n `Failed to resume recording: ${error instanceof Error ? error.message : 'unknown error'}`\n )\n }\n }\n\n /**\n * Initializes the compressed media recorder if compression is enabled\n * Sets up event handlers for compressed audio data\n */\n private initializeCompressedRecorder() {\n try {\n const mimeType = 'audio/webm;codecs=opus'\n if (!MediaRecorder.isTypeSupported(mimeType)) {\n this.logger?.warn(\n 'Opus compression not supported in this browser'\n )\n return\n }\n\n this.compressedMediaRecorder = new MediaRecorder(\n this.source.mediaStream,\n {\n mimeType,\n audioBitsPerSecond:\n this.config.output?.compressed?.bitrate ?? 128000,\n }\n )\n\n this.compressedMediaRecorder.ondataavailable = (event) => {\n if (event.data.size > 0) {\n // Store the compressed chunk for final blob creation\n this.compressedChunks.push(event.data)\n this.compressedSize += event.data.size\n\n // Store the pending compressed chunk for the next PCM chunk to use\n this.pendingCompressedChunk = event.data\n }\n }\n } catch (error) {\n this.logger?.error(\n 'Failed to initialize compressed recorder:',\n error\n )\n // Setting to null to indicate initialization failed\n this.compressedMediaRecorder = null\n }\n }\n\n /**\n * Processes features if enabled\n */\n processFeatures(\n chunk: Float32Array,\n sampleRate: number,\n chunkPosition: number,\n startPosition: number,\n endPosition: number,\n samples: number\n ) {\n if (this.config.enableProcessing && this.featureExtractorWorker) {\n this.featureExtractorWorker.postMessage({\n command: 'process',\n channelData: chunk,\n sampleRate,\n segmentDurationMs:\n this.config.segmentDurationMs ??\n DEFAULT_SEGMENT_DURATION_MS, // Default to 100ms\n bitDepth: this.bitDepth,\n fullAudioDurationMs: chunkPosition * 1000,\n numberOfChannels: this.numberOfChannels,\n features: this.config.features,\n intervalAnalysis: this.config.intervalAnalysis,\n startPosition,\n endPosition,\n samples,\n })\n }\n }\n\n /**\n * Sets up detection for device disconnection events\n */\n private setupDeviceDisconnectionDetection() {\n if (!this.mediaStream) return\n\n // Function to handle track ending (which happens on device disconnection)\n const handleTrackEnded = () => {\n this.logger?.warn('Audio track ended - device disconnected')\n this._isDeviceDisconnected = true\n\n // Use the callback to notify parent component about device disconnection\n if (this.onInterruptionCallback) {\n this.onInterruptionCallback({\n reason: 'deviceDisconnected',\n isPaused: true,\n timestamp: Date.now(),\n })\n this.logger?.debug('Notified about device disconnection')\n }\n\n // Ensure we disconnect nodes to prevent zombie recordings\n if (this.audioWorkletNode) {\n this.audioWorkletNode.port.postMessage({\n command: 'deviceDisconnected',\n })\n\n try {\n this.source.disconnect(this.audioWorkletNode)\n this.audioWorkletNode.disconnect()\n } catch (e) {\n // Ignore disconnection errors as the track might already be gone\n this.logger?.warn(\n 'Error disconnecting audioWorkletNode:',\n e\n )\n }\n }\n }\n\n // Add listeners to all audio tracks\n const tracks = this.mediaStream.getAudioTracks()\n tracks.forEach((track) => {\n track.addEventListener('ended', handleTrackEnded)\n })\n\n // Store the handler for cleanup\n this.deviceDisconnectionHandler = () => {\n tracks.forEach((track) => {\n track.removeEventListener('ended', handleTrackEnded)\n })\n }\n }\n\n /**\n * Explicitly set the position for continuous recording across device switches\n * @param position The position in seconds to continue from\n */\n setPosition(position: number): void {\n if (position >= 0) {\n this.position = position\n this.logger?.debug(`Position explicitly set to ${position} seconds`)\n } else {\n this.logger?.warn(`Invalid position value: ${position}, ignoring`)\n }\n }\n\n /**\n * Get the current position in seconds\n * @returns The current position\n */\n getPosition(): number {\n return this.position\n }\n\n /**\n * Gets the current compressed chunks\n * @returns Array of current compressed audio chunks\n */\n getCompressedChunks(): Blob[] {\n return [...this.compressedChunks]\n }\n\n /**\n * Sets the compressed chunks from a previous recorder\n * @param chunks Array of compressed chunks from a previous recorder\n */\n setCompressedChunks(chunks: Blob[]): void {\n if (chunks && chunks.length > 0) {\n this.logger?.debug(\n `Adding ${chunks.length} compressed chunks from previous device`\n )\n this.compressedChunks = [...chunks, ...this.compressedChunks]\n // Update size\n this.compressedSize = this.compressedChunks.reduce(\n (size, chunk) => size + chunk.size,\n 0\n )\n }\n }\n}\n"]}
@@ -11,6 +11,8 @@ function useAudioDevices() {
11
11
  const [currentDevice, setCurrentDevice] = (0, react_1.useState)(null);
12
12
  const [loading, setLoading] = (0, react_1.useState)(true);
13
13
  const [error, setError] = (0, react_1.useState)(null);
14
+ // Generate unique instance ID for debugging
15
+ const instanceId = (0, react_1.useId)().replace(/:/g, '').slice(0, 5);
14
16
  // Load devices on mount
15
17
  (0, react_1.useEffect)(() => {
16
18
  let isMounted = true;
@@ -28,7 +30,9 @@ function useAudioDevices() {
28
30
  setCurrentDevice(device);
29
31
  }
30
32
  catch (err) {
31
- console.error('Failed to load audio devices:', err);
33
+ AudioDeviceManager_1.audioDeviceManager
34
+ .getLogger()
35
+ ?.error('Failed to load audio devices:', err);
32
36
  if (isMounted)
33
37
  setError(err instanceof Error
34
38
  ? err
@@ -42,16 +46,23 @@ function useAudioDevices() {
42
46
  loadDevices();
43
47
  // Set up device change listener
44
48
  const removeListener = AudioDeviceManager_1.audioDeviceManager.addDeviceChangeListener((updatedDevices) => {
49
+ AudioDeviceManager_1.audioDeviceManager
50
+ .getLogger()
51
+ ?.debug(`🎛️ useAudioDevices [${instanceId}] received device change. Count: ${updatedDevices.length}`);
45
52
  if (isMounted) {
46
53
  setDevices(updatedDevices);
47
54
  // If our current device is no longer available, update it
48
55
  if (currentDevice &&
49
56
  !updatedDevices.some((d) => d.id === currentDevice.id)) {
57
+ AudioDeviceManager_1.audioDeviceManager
58
+ .getLogger()
59
+ ?.debug(`🎛️ useAudioDevices [${instanceId}] Current device ${currentDevice.id} no longer available, updating`);
50
60
  AudioDeviceManager_1.audioDeviceManager
51
61
  .getCurrentDevice()
52
62
  .then((newDevice) => {
53
- if (isMounted)
63
+ if (isMounted) {
54
64
  setCurrentDevice(newDevice);
65
+ }
55
66
  });
56
67
  }
57
68
  }
@@ -79,7 +90,9 @@ function useAudioDevices() {
79
90
  return success;
80
91
  }
81
92
  catch (err) {
82
- console.error('Failed to select audio device:', err);
93
+ AudioDeviceManager_1.audioDeviceManager
94
+ .getLogger()
95
+ ?.error('Failed to select audio device:', err);
83
96
  setError(err instanceof Error
84
97
  ? err
85
98
  : new Error('Failed to select audio device'));
@@ -106,7 +119,9 @@ function useAudioDevices() {
106
119
  return success;
107
120
  }
108
121
  catch (err) {
109
- console.error('Failed to reset to default audio device:', err);
122
+ AudioDeviceManager_1.audioDeviceManager
123
+ .getLogger()
124
+ ?.error('Failed to reset to default audio device:', err);
110
125
  setError(err instanceof Error
111
126
  ? err
112
127
  : new Error('Failed to reset to default audio device'));
@@ -131,7 +146,9 @@ function useAudioDevices() {
131
146
  return updatedDevices;
132
147
  }
133
148
  catch (err) {
134
- console.error('Failed to refresh audio devices:', err);
149
+ AudioDeviceManager_1.audioDeviceManager
150
+ .getLogger()
151
+ ?.error('Failed to refresh audio devices:', err);
135
152
  setError(err instanceof Error
136
153
  ? err
137
154
  : new Error('Failed to refresh audio devices'));
@@ -141,6 +158,13 @@ function useAudioDevices() {
141
158
  setLoading(false);
142
159
  }
143
160
  }, []);
161
+ /**
162
+ * Initialize device detection
163
+ * Useful for restarting device detection if it failed initially
164
+ */
165
+ const initializeDeviceDetection = (0, react_1.useCallback)(() => {
166
+ AudioDeviceManager_1.audioDeviceManager.initializeDeviceDetection();
167
+ }, []);
144
168
  return {
145
169
  devices,
146
170
  currentDevice,
@@ -149,6 +173,7 @@ function useAudioDevices() {
149
173
  selectDevice,
150
174
  resetToDefaultDevice,
151
175
  refreshDevices,
176
+ initializeDeviceDetection,
152
177
  };
153
178
  }
154
179
  //# sourceMappingURL=useAudioDevices.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAudioDevices.js","sourceRoot":"","sources":["../../../src/hooks/useAudioDevices.ts"],"names":[],"mappings":";;AAQA,0CA2KC;AAnLD,iCAAwD;AAExD,8DAA0D;AAG1D;;GAEG;AACH,SAAgB,eAAe;IAC3B,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,IAAA,gBAAQ,EAAgB,EAAE,CAAC,CAAA;IACzD,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,IAAA,gBAAQ,EAAqB,IAAI,CAA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M,CAAC,CAAA;YAExB,OAAO,cAAc,CAAA;QACzB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,kCAAkC,EAAE,GAAG,CAAC,CAAA;YACtD,QAAQ,CACJ,GAAG,YAAY,KAAK;gBAChB,CAAC,CAAC,GAAG;gBACL,CAAC,CAAC,IAAI,KAAK,CAAC,iCAAiC,CAAC,CACrD,CAAA;YACD,OAAO,EAAE,CAAA;QACb,CAAC;gBAAS,CAAC;YACP,UAAU,CAAC,KAAK,CAAC,CAAA;QACrB,CAAC;IACL,CAAC,EAAE,EAAE,CAAC,CAAA;IAEN,OAAO;QACH,OAAO;QACP,aAAa;QACb,OAAO;QACP,KAAK;QACL,YAAY;QACZ,oBAAoB;QACpB,cAAc;KACjB,CAAA;AACL,CAAC","sourcesContent":["import { useCallback, useEffect, useState } from 'react'\n\nimport { audioDeviceManager } from '../AudioDeviceManager'\nimport { AudioDevice } from '../ExpoAudioStream.types'\n\n/**\n * React hook for managing audio input devices\n */\nexport function useAudioDevices() {\n const [devices, setDevices] = useState<AudioDevice[]>([])\n const [currentDevice, setCurrentDevice] = useState<AudioDevice | null>(null)\n const [loading, setLoading] = useState(true)\n const [error, setError] = useState<Error | null>(null)\n\n // Load devices on mount\n useEffect(() => {\n let isMounted = true\n\n const loadDevices = async () => {\n try {\n setLoading(true)\n setError(null)\n\n // Load available devices\n const availableDevices =\n await audioDeviceManager.getAvailableDevices()\n if (isMounted) setDevices(availableDevices)\n\n // Get current device\n const device = await audioDeviceManager.getCurrentDevice()\n if (isMounted) setCurrentDevice(device)\n } catch (err) {\n console.error('Failed to load audio devices:', err)\n if (isMounted)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to load audio devices')\n )\n } finally {\n if (isMounted) setLoading(false)\n }\n }\n\n loadDevices()\n\n // Set up device change listener\n const removeListener = audioDeviceManager.addDeviceChangeListener(\n (updatedDevices: AudioDevice[]) => {\n if (isMounted) {\n setDevices(updatedDevices)\n\n // If our current device is no longer available, update it\n if (\n currentDevice &&\n !updatedDevices.some(\n (d: AudioDevice) => d.id === currentDevice.id\n )\n ) {\n audioDeviceManager\n .getCurrentDevice()\n .then((newDevice: AudioDevice | null) => {\n if (isMounted) setCurrentDevice(newDevice)\n })\n }\n }\n }\n )\n\n return () => {\n isMounted = false\n removeListener()\n }\n }, [])\n\n /**\n * Select a specific audio input device\n * @param deviceId The ID of the device to select\n * @returns Promise resolving to a boolean indicating success\n */\n const selectDevice = useCallback(\n async (deviceId: string): Promise<boolean> => {\n try {\n setLoading(true)\n setError(null)\n\n const success = await audioDeviceManager.selectDevice(deviceId)\n\n if (success) {\n // Get the updated current device after selection\n const device = await audioDeviceManager.getCurrentDevice()\n setCurrentDevice(device)\n }\n\n return success\n } catch (err) {\n console.error('Failed to select audio device:', err)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to select audio device')\n )\n return false\n } finally {\n setLoading(false)\n }\n },\n []\n )\n\n /**\n * Reset to the default audio input device\n * @returns Promise resolving to a boolean indicating success\n */\n const resetToDefaultDevice = useCallback(async (): Promise<boolean> => {\n try {\n setLoading(true)\n setError(null)\n\n const success = await audioDeviceManager.resetToDefaultDevice()\n\n if (success) {\n // Get the updated current device after reset\n const device = await audioDeviceManager.getCurrentDevice()\n setCurrentDevice(device)\n }\n\n return success\n } catch (err) {\n console.error('Failed to reset to default audio device:', err)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to reset to default audio device')\n )\n return false\n } finally {\n setLoading(false)\n }\n }, [])\n\n /**\n * Refresh the list of available devices\n */\n const refreshDevices = useCallback(async (): Promise<AudioDevice[]> => {\n try {\n setLoading(true)\n setError(null)\n\n const updatedDevices = await audioDeviceManager.refreshDevices()\n setDevices(updatedDevices)\n\n // Also refresh the current device\n const device = await audioDeviceManager.getCurrentDevice()\n setCurrentDevice(device)\n\n return updatedDevices\n } catch (err) {\n console.error('Failed to refresh audio devices:', err)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to refresh audio devices')\n )\n return []\n } finally {\n setLoading(false)\n }\n }, [])\n\n return {\n devices,\n currentDevice,\n loading,\n error,\n selectDevice,\n resetToDefaultDevice,\n refreshDevices,\n }\n}\n"]}
1
+ {"version":3,"file":"useAudioDevices.js","sourceRoot":"","sources":["../../../src/hooks/useAudioDevices.ts"],"names":[],"mappings":";;AAQA,0CA4MC;AApND,iCAA+D;AAE/D,8DAA0D;AAG1D;;GAEG;AACH,SAAgB,eAAe;IAC3B,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,IAAA,gBAAQ,EAAgB,EAAE,CAAC,CAAA;IACzD,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,IAAA,gBAAQ,EAAqB,IAAI,CAAC,CAAA;IAC5E,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,IAAA,gBAAQ,EAAC,IAAI,CAAC,CAAA;IAC5C,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,IAAA,gBAAQ,EAAe,IAAI,CAAC,CAAA;IAEtD,4CAA4C;IAC5C,MAAM,UAAU,GAAG,IAAA,aAAK,GAAE,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;IAExD,wBAAwB;IACxB,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,IAAI,SAAS,GAAG,IAAI,CAAA;QAEpB,MAAM,WAAW,GAAG,KAAK,IAAI,EAAE;YAC3B,IAAI,CAAC;gBACD,UAAU,CAAC,IAAI,CAAC,CAAA;gBAChB,QAAQ,CAAC,IAAI,CAAC,CAAA;gBAEd,yBAAyB;gBACzB,MAAM,gBAAgB,GAClB,MAAM,uCAAkB,CAAC,mBAAmB,EAAE,CAAA;gBAClD,IAAI,SAAS;oBAAE,UAAU,CAAC,gBAAgB,CAAC,CAAA;gBAE3C,qBAAqB;gBACrB,MAAM,MAAM,GAAG,MAAM,uCAAkB,CAAC,gBAAgB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CACrD,CAAA;YACD,OAAO,EAAE,CAAA;QACb,CAAC;gBAAS,CAAC;YACP,UAAU,CAAC,KAAK,CAAC,CAAA;QACrB,CAAC;IACL,CAAC,EAAE,EAAE,CAAC,CAAA;IAEN;;;OAGG;IACH,MAAM,yBAAyB,GAAG,IAAA,mBAAW,EAAC,GAAG,EAAE;QAC/C,uCAAkB,CAAC,yBAAyB,EAAE,CAAA;IAClD,CAAC,EAAE,EAAE,CAAC,CAAA;IAEN,OAAO;QACH,OAAO;QACP,aAAa;QACb,OAAO;QACP,KAAK;QACL,YAAY;QACZ,oBAAoB;QACpB,cAAc;QACd,yBAAyB;KAC5B,CAAA;AACL,CAAC","sourcesContent":["import { useCallback, useEffect, useState, useId } from 'react'\n\nimport { audioDeviceManager } from '../AudioDeviceManager'\nimport { AudioDevice } from '../ExpoAudioStream.types'\n\n/**\n * React hook for managing audio input devices\n */\nexport function useAudioDevices() {\n const [devices, setDevices] = useState<AudioDevice[]>([])\n const [currentDevice, setCurrentDevice] = useState<AudioDevice | null>(null)\n const [loading, setLoading] = useState(true)\n const [error, setError] = useState<Error | null>(null)\n\n // Generate unique instance ID for debugging\n const instanceId = useId().replace(/:/g, '').slice(0, 5)\n\n // Load devices on mount\n useEffect(() => {\n let isMounted = true\n\n const loadDevices = async () => {\n try {\n setLoading(true)\n setError(null)\n\n // Load available devices\n const availableDevices =\n await audioDeviceManager.getAvailableDevices()\n if (isMounted) setDevices(availableDevices)\n\n // Get current device\n const device = await audioDeviceManager.getCurrentDevice()\n if (isMounted) setCurrentDevice(device)\n } catch (err) {\n audioDeviceManager\n .getLogger()\n ?.error('Failed to load audio devices:', err)\n if (isMounted)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to load audio devices')\n )\n } finally {\n if (isMounted) setLoading(false)\n }\n }\n\n loadDevices()\n\n // Set up device change listener\n const removeListener = audioDeviceManager.addDeviceChangeListener(\n (updatedDevices: AudioDevice[]) => {\n audioDeviceManager\n .getLogger()\n ?.debug(\n `🎛️ useAudioDevices [${instanceId}] received device change. Count: ${updatedDevices.length}`\n )\n\n if (isMounted) {\n setDevices(updatedDevices)\n\n // If our current device is no longer available, update it\n if (\n currentDevice &&\n !updatedDevices.some(\n (d: AudioDevice) => d.id === currentDevice.id\n )\n ) {\n audioDeviceManager\n .getLogger()\n ?.debug(\n `🎛️ useAudioDevices [${instanceId}] Current device ${currentDevice.id} no longer available, updating`\n )\n audioDeviceManager\n .getCurrentDevice()\n .then((newDevice: AudioDevice | null) => {\n if (isMounted) {\n setCurrentDevice(newDevice)\n }\n })\n }\n }\n }\n )\n\n return () => {\n isMounted = false\n removeListener()\n }\n }, [])\n\n /**\n * Select a specific audio input device\n * @param deviceId The ID of the device to select\n * @returns Promise resolving to a boolean indicating success\n */\n const selectDevice = useCallback(\n async (deviceId: string): Promise<boolean> => {\n try {\n setLoading(true)\n setError(null)\n\n const success = await audioDeviceManager.selectDevice(deviceId)\n\n if (success) {\n // Get the updated current device after selection\n const device = await audioDeviceManager.getCurrentDevice()\n setCurrentDevice(device)\n }\n\n return success\n } catch (err) {\n audioDeviceManager\n .getLogger()\n ?.error('Failed to select audio device:', err)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to select audio device')\n )\n return false\n } finally {\n setLoading(false)\n }\n },\n []\n )\n\n /**\n * Reset to the default audio input device\n * @returns Promise resolving to a boolean indicating success\n */\n const resetToDefaultDevice = useCallback(async (): Promise<boolean> => {\n try {\n setLoading(true)\n setError(null)\n\n const success = await audioDeviceManager.resetToDefaultDevice()\n\n if (success) {\n // Get the updated current device after reset\n const device = await audioDeviceManager.getCurrentDevice()\n setCurrentDevice(device)\n }\n\n return success\n } catch (err) {\n audioDeviceManager\n .getLogger()\n ?.error('Failed to reset to default audio device:', err)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to reset to default audio device')\n )\n return false\n } finally {\n setLoading(false)\n }\n }, [])\n\n /**\n * Refresh the list of available devices\n */\n const refreshDevices = useCallback(async (): Promise<AudioDevice[]> => {\n try {\n setLoading(true)\n setError(null)\n\n const updatedDevices = await audioDeviceManager.refreshDevices()\n setDevices(updatedDevices)\n\n // Also refresh the current device\n const device = await audioDeviceManager.getCurrentDevice()\n setCurrentDevice(device)\n\n return updatedDevices\n } catch (err) {\n audioDeviceManager\n .getLogger()\n ?.error('Failed to refresh audio devices:', err)\n setError(\n err instanceof Error\n ? err\n : new Error('Failed to refresh audio devices')\n )\n return []\n } finally {\n setLoading(false)\n }\n }, [])\n\n /**\n * Initialize device detection\n * Useful for restarting device detection if it failed initially\n */\n const initializeDeviceDetection = useCallback(() => {\n audioDeviceManager.initializeDeviceDetection()\n }, [])\n\n return {\n devices,\n currentDevice,\n loading,\n error,\n selectDevice,\n resetToDefaultDevice,\n refreshDevices,\n initializeDeviceDetection,\n }\n}\n"]}
@@ -7,6 +7,7 @@ exports.useAudioRecorder = useAudioRecorder;
7
7
  // src/useAudioRecorder.ts
8
8
  const expo_modules_core_1 = require("expo-modules-core");
9
9
  const react_1 = require("react");
10
+ const AudioDeviceManager_1 = require("./AudioDeviceManager");
10
11
  const ExpoAudioStreamModule_1 = __importDefault(require("./ExpoAudioStreamModule"));
11
12
  const events_1 = require("./events");
12
13
  const defaultAnalysis = {
@@ -25,6 +26,7 @@ const defaultAnalysis = {
25
26
  min: Number.POSITIVE_INFINITY,
26
27
  max: Number.NEGATIVE_INFINITY,
27
28
  },
29
+ extractionTimeMs: 0,
28
30
  };
29
31
  function audioRecorderReducer(state, action) {
30
32
  switch (action.type) {
@@ -84,6 +86,10 @@ function audioRecorderReducer(state, action) {
84
86
  }
85
87
  }
86
88
  function useAudioRecorder({ logger, audioWorkletUrl, featuresExtratorUrl, } = {}) {
89
+ // Initialize AudioDeviceManager with logger (once)
90
+ if (logger) {
91
+ AudioDeviceManager_1.audioDeviceManager.setLogger(logger);
92
+ }
87
93
  const [state, dispatch] = (0, react_1.useReducer)(audioRecorderReducer, {
88
94
  isRecording: false,
89
95
  isPaused: false,
@@ -117,6 +123,8 @@ function useAudioRecorder({ logger, audioWorkletUrl, featuresExtratorUrl, } = {}
117
123
  compression: undefined,
118
124
  });
119
125
  const recordingConfigRef = (0, react_1.useRef)(null);
126
+ // Generate unique instance ID for debugging
127
+ const instanceId = (0, react_1.useId)().replace(/:/g, '').slice(0, 5);
120
128
  const handleAudioAnalysis = (0, react_1.useCallback)(async ({ analysis, visualizationDuration, }) => {
121
129
  const savedAnalysisData = analysisRef.current || {
122
130
  ...defaultAnalysis,
@@ -313,7 +321,7 @@ function useAudioRecorder({ logger, audioWorkletUrl, featuresExtratorUrl, } = {}
313
321
  logger?.debug(`start recoding`, recordingOptions);
314
322
  analysisRef.current = { ...defaultAnalysis }; // Reset analysis data
315
323
  fullAnalysisRef.current = { ...defaultAnalysis };
316
- const { onAudioStream, ...options } = recordingOptions;
324
+ const { onAudioStream, onRecordingInterrupted, onAudioAnalysis, ...options } = recordingOptions;
317
325
  const { enableProcessing } = options;
318
326
  const maxRecentDataDuration = 10000; // TODO compute maxRecentDataDuration based on screen dimensions
319
327
  if (typeof onAudioStream === 'function') {
@@ -348,7 +356,7 @@ function useAudioRecorder({ logger, audioWorkletUrl, featuresExtratorUrl, } = {}
348
356
  logger?.debug(`preparing recording`, recordingOptions);
349
357
  analysisRef.current = { ...defaultAnalysis }; // Reset analysis data
350
358
  fullAnalysisRef.current = { ...defaultAnalysis };
351
- const { onAudioStream, ...options } = recordingOptions;
359
+ const { onAudioStream, onRecordingInterrupted, onAudioAnalysis, ...options } = recordingOptions;
352
360
  // Store onAudioStream for later use when recording starts
353
361
  if (typeof onAudioStream === 'function') {
354
362
  onAudioStreamRef.current = onAudioStream;
@@ -370,6 +378,7 @@ function useAudioRecorder({ logger, audioWorkletUrl, featuresExtratorUrl, } = {}
370
378
  analysisListenerRef.current = null;
371
379
  }
372
380
  onAudioStreamRef.current = null;
381
+ // Note: We deliberately DON'T clear recordingConfigRef here to preserve interruption callback
373
382
  logger?.debug(`recording stopped`, stopResult);
374
383
  dispatch({ type: 'STOP' });
375
384
  return stopResult;
@@ -414,27 +423,63 @@ function useAudioRecorder({ logger, audioWorkletUrl, featuresExtratorUrl, } = {}
414
423
  }, [handleAudioEvent, handleAudioAnalysis]);
415
424
  (0, react_1.useEffect)(() => {
416
425
  // Add event subscription for recording interruptions
417
- logger?.debug('Setting up recording interruption listener');
426
+ logger?.debug(`Setting up recording interruption listener [${instanceId}]`);
418
427
  const subscription = (0, events_1.addRecordingInterruptionListener)((event) => {
419
- logger?.debug('Received recording interruption event:', event);
428
+ logger?.debug(`[${instanceId}] Received recording interruption event:`, event);
429
+ // Handle device disconnection for UI updates
430
+ if (event.reason === 'deviceDisconnected') {
431
+ logger?.debug(`[${instanceId}] Device disconnected - temporarily hiding last device from UI`);
432
+ // Get current device list before the native layer updates
433
+ const currentDevices = AudioDeviceManager_1.audioDeviceManager.getRawDevices();
434
+ // Wait a moment for native layer to update, then compare
435
+ setTimeout(async () => {
436
+ try {
437
+ // Get updated devices without notifying yet
438
+ const updatedDevices = await AudioDeviceManager_1.audioDeviceManager.getAvailableDevices({
439
+ refresh: true,
440
+ });
441
+ // Find missing devices by comparing lists
442
+ const missingDevices = currentDevices.filter((oldDevice) => !updatedDevices.some((newDevice) => newDevice.id === oldDevice.id));
443
+ if (missingDevices.length > 0) {
444
+ // Mark all missing devices as disconnected (silently)
445
+ missingDevices.forEach((missingDevice) => {
446
+ logger?.debug(`[${instanceId}] Confirmed disconnected device: ${missingDevice.name} (${missingDevice.id})`);
447
+ AudioDeviceManager_1.audioDeviceManager.markDeviceAsDisconnected(missingDevice.id, false);
448
+ });
449
+ }
450
+ // Notify listeners once with the final filtered state
451
+ AudioDeviceManager_1.audioDeviceManager.notifyListeners();
452
+ }
453
+ catch (error) {
454
+ logger?.warn(`[${instanceId}] Error in delayed device disconnection handling:`, error);
455
+ }
456
+ }, 500); // 500ms delay to let native layer update
457
+ }
458
+ else if (event.reason === 'deviceConnected') {
459
+ // Device reconnected - force refresh to show it immediately
460
+ logger?.debug(`[${instanceId}] Device connected, forcing refresh`);
461
+ AudioDeviceManager_1.audioDeviceManager.forceRefreshDevices();
462
+ }
420
463
  // Check if we have a callback configured
464
+ logger?.debug(`[${instanceId}] recordingConfigRef.current exists:`, !!recordingConfigRef.current);
421
465
  if (recordingConfigRef.current?.onRecordingInterrupted) {
422
466
  try {
467
+ logger?.debug(`[${instanceId}] Calling recording interruption callback`);
423
468
  recordingConfigRef.current.onRecordingInterrupted(event);
424
469
  }
425
470
  catch (error) {
426
- logger?.error('Error in recording interruption callback:', error);
471
+ logger?.error(`[${instanceId}] Error in recording interruption callback:`, error);
427
472
  }
428
473
  }
429
474
  else {
430
- logger?.debug('No recording interruption callback configured');
475
+ logger?.debug(`[${instanceId}] No recording interruption callback configured`);
431
476
  }
432
477
  });
433
478
  return () => {
434
- logger?.debug('Removing recording interruption listener');
479
+ logger?.debug(`[${instanceId}] Removing recording interruption listener`);
435
480
  subscription.remove();
436
481
  };
437
- }, []); // Empty dependency array since we want this to run once
482
+ }, [instanceId, logger]); // Include instanceId and logger in dependencies
438
483
  return {
439
484
  prepareRecording,
440
485
  startRecording,