@siteed/expo-audio-studio 2.4.1 → 2.6.0

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 (85) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/README.md +25 -0
  3. package/android/src/main/java/net/siteed/audiostream/AudioAnalysisData.kt +22 -0
  4. package/android/src/main/java/net/siteed/audiostream/AudioDeviceManager.kt +1501 -0
  5. package/android/src/main/java/net/siteed/audiostream/AudioFileHandler.kt +10 -5
  6. package/android/src/main/java/net/siteed/audiostream/AudioNotificationsManager.kt +27 -25
  7. package/android/src/main/java/net/siteed/audiostream/AudioProcessor.kt +73 -71
  8. package/android/src/main/java/net/siteed/audiostream/AudioRecorderManager.kt +576 -252
  9. package/android/src/main/java/net/siteed/audiostream/Constants.kt +17 -1
  10. package/android/src/main/java/net/siteed/audiostream/ExpoAudioStreamModule.kt +419 -155
  11. package/android/src/main/java/net/siteed/audiostream/LogUtils.kt +65 -0
  12. package/android/src/main/java/net/siteed/audiostream/RecordingConfig.kt +9 -1
  13. package/build/AudioAnalysis/AudioAnalysis.types.js.map +1 -1
  14. package/build/AudioDeviceManager.d.ts +107 -0
  15. package/build/AudioDeviceManager.d.ts.map +1 -0
  16. package/build/AudioDeviceManager.js +493 -0
  17. package/build/AudioDeviceManager.js.map +1 -0
  18. package/build/AudioRecorder.provider.d.ts.map +1 -1
  19. package/build/AudioRecorder.provider.js +3 -0
  20. package/build/AudioRecorder.provider.js.map +1 -1
  21. package/build/ExpoAudioStream.types.d.ts +104 -1
  22. package/build/ExpoAudioStream.types.d.ts.map +1 -1
  23. package/build/ExpoAudioStream.types.js +7 -1
  24. package/build/ExpoAudioStream.types.js.map +1 -1
  25. package/build/ExpoAudioStream.web.d.ts +37 -0
  26. package/build/ExpoAudioStream.web.d.ts.map +1 -1
  27. package/build/ExpoAudioStream.web.js +478 -62
  28. package/build/ExpoAudioStream.web.js.map +1 -1
  29. package/build/ExpoAudioStreamModule.d.ts.map +1 -1
  30. package/build/ExpoAudioStreamModule.js +20 -0
  31. package/build/ExpoAudioStreamModule.js.map +1 -1
  32. package/build/WebRecorder.web.d.ts +74 -11
  33. package/build/WebRecorder.web.d.ts.map +1 -1
  34. package/build/WebRecorder.web.js +390 -74
  35. package/build/WebRecorder.web.js.map +1 -1
  36. package/build/hooks/useAudioDevices.d.ts +14 -0
  37. package/build/hooks/useAudioDevices.d.ts.map +1 -0
  38. package/build/hooks/useAudioDevices.js +151 -0
  39. package/build/hooks/useAudioDevices.js.map +1 -0
  40. package/build/index.d.ts +2 -0
  41. package/build/index.d.ts.map +1 -1
  42. package/build/index.js +4 -0
  43. package/build/index.js.map +1 -1
  44. package/build/useAudioRecorder.d.ts +1 -0
  45. package/build/useAudioRecorder.d.ts.map +1 -1
  46. package/build/useAudioRecorder.js +20 -1
  47. package/build/useAudioRecorder.js.map +1 -1
  48. package/build/utils/BlobFix.d.ts.map +1 -1
  49. package/build/utils/BlobFix.js +2 -2
  50. package/build/utils/BlobFix.js.map +1 -1
  51. package/build/utils/writeWavHeader.d.ts +3 -18
  52. package/build/utils/writeWavHeader.d.ts.map +1 -1
  53. package/build/utils/writeWavHeader.js +19 -26
  54. package/build/utils/writeWavHeader.js.map +1 -1
  55. package/build/workers/InlineFeaturesExtractor.web.d.ts +1 -1
  56. package/build/workers/InlineFeaturesExtractor.web.d.ts.map +1 -1
  57. package/build/workers/InlineFeaturesExtractor.web.js +27 -26
  58. package/build/workers/InlineFeaturesExtractor.web.js.map +1 -1
  59. package/build/workers/inlineAudioWebWorker.web.d.ts +1 -1
  60. package/build/workers/inlineAudioWebWorker.web.d.ts.map +1 -1
  61. package/build/workers/inlineAudioWebWorker.web.js +25 -1
  62. package/build/workers/inlineAudioWebWorker.web.js.map +1 -1
  63. package/ios/AudioDeviceManager.swift +654 -0
  64. package/ios/AudioStreamManager.swift +964 -760
  65. package/ios/ExpoAudioStreamModule.swift +174 -19
  66. package/ios/Features.swift +1 -1
  67. package/ios/ISSUE_IOS.md +45 -0
  68. package/ios/Logger.swift +13 -1
  69. package/ios/RecordingSettings.swift +12 -0
  70. package/package.json +2 -2
  71. package/src/AudioAnalysis/AudioAnalysis.types.ts +2 -2
  72. package/src/AudioDeviceManager.ts +571 -0
  73. package/src/AudioRecorder.provider.tsx +3 -0
  74. package/src/ExpoAudioStream.types.ts +113 -1
  75. package/src/ExpoAudioStream.web.ts +609 -69
  76. package/src/ExpoAudioStreamModule.ts +23 -0
  77. package/src/WebRecorder.web.ts +482 -92
  78. package/src/hooks/useAudioDevices.ts +180 -0
  79. package/src/index.ts +6 -0
  80. package/src/types/crc-32.d.ts +6 -6
  81. package/src/useAudioRecorder.tsx +27 -1
  82. package/src/utils/BlobFix.ts +6 -4
  83. package/src/utils/writeWavHeader.ts +26 -25
  84. package/src/workers/InlineFeaturesExtractor.web.tsx +27 -26
  85. package/src/workers/inlineAudioWebWorker.web.tsx +25 -1
@@ -0,0 +1,493 @@
1
+ import { EventEmitter } from 'expo-modules-core';
2
+ import { Platform } from 'react-native';
3
+ import { DeviceDisconnectionBehavior, } from './ExpoAudioStream.types';
4
+ import ExpoAudioStreamModule from './ExpoAudioStreamModule';
5
+ // Default device fallback for web and unsupported platforms
6
+ const DEFAULT_DEVICE = {
7
+ id: 'default',
8
+ name: 'Default Microphone',
9
+ type: 'builtin_mic',
10
+ isDefault: true,
11
+ isAvailable: true,
12
+ capabilities: {
13
+ sampleRates: [16000, 44100, 48000],
14
+ channelCounts: [1, 2],
15
+ bitDepths: [16, 24, 32],
16
+ hasEchoCancellation: true,
17
+ hasNoiseSuppression: true,
18
+ hasAutomaticGainControl: true,
19
+ },
20
+ };
21
+ // Helper function to map raw object to AudioDevice interface
22
+ // This handles potential inconsistencies from the native module
23
+ function mapRawDeviceToAudioDevice(rawDevice) {
24
+ const capabilities = rawDevice.capabilities || {};
25
+ return {
26
+ id: rawDevice.id || 'unknown',
27
+ name: rawDevice.name || 'Unknown Device',
28
+ type: rawDevice.type || 'unknown',
29
+ isDefault: rawDevice.isDefault || false,
30
+ isAvailable: rawDevice.isAvailable !== undefined ? rawDevice.isAvailable : true, // Default to true if undefined
31
+ capabilities: {
32
+ sampleRates: capabilities.sampleRates || [16000, 44100, 48000], // Provide defaults
33
+ channelCounts: capabilities.channelCounts || [1, 2],
34
+ bitDepths: capabilities.bitDepths || [16, 24, 32],
35
+ hasEchoCancellation: capabilities.hasEchoCancellation,
36
+ hasNoiseSuppression: capabilities.hasNoiseSuppression,
37
+ hasAutomaticGainControl: capabilities.hasAutomaticGainControl,
38
+ },
39
+ };
40
+ }
41
+ /**
42
+ * Class that provides a cross-platform API for managing audio input devices
43
+ */
44
+ export class AudioDeviceManager {
45
+ eventEmitter;
46
+ currentDeviceId = null;
47
+ availableDevices = [];
48
+ deviceChangeListeners = new Set();
49
+ deviceListeners = new Set();
50
+ lastRefreshTime = 0;
51
+ refreshInProgress = false;
52
+ refreshDebounceMs = 500; // Minimum 500ms between refreshes
53
+ logger;
54
+ constructor(options) {
55
+ this.eventEmitter = new EventEmitter(ExpoAudioStreamModule);
56
+ this.logger = options?.logger;
57
+ // Listen for device change events from native modules if not on web
58
+ if (Platform.OS !== 'web') {
59
+ // Store the last event type to avoid duplicates
60
+ let lastEventType = null;
61
+ let lastEventTime = 0;
62
+ this.eventEmitter.addListener('deviceChangedEvent', (event) => {
63
+ // Skip processing duplicate events that occur too close together
64
+ const now = Date.now();
65
+ const isSimilarEvent = lastEventType === event.type &&
66
+ now - lastEventTime < this.refreshDebounceMs;
67
+ if (isSimilarEvent) {
68
+ this.logger?.debug(`Skipping similar device event (${event.type}) received too soon`);
69
+ return;
70
+ }
71
+ // Update the last event tracking
72
+ lastEventType = event.type;
73
+ lastEventTime = now;
74
+ // Only refresh on meaningful events
75
+ if (event.type === 'deviceConnected' ||
76
+ event.type === 'deviceDisconnected' ||
77
+ event.type === 'routeChanged') {
78
+ this.logger?.debug(`Processing device event: ${event.type}`);
79
+ // Refresh devices and notify listeners regardless of the direct return value
80
+ this.refreshDevices();
81
+ }
82
+ });
83
+ }
84
+ }
85
+ /**
86
+ * Initialize the device manager with a logger
87
+ * @param logger A logger instance that implements the ConsoleLike interface
88
+ * @returns The manager instance for chaining
89
+ */
90
+ initWithLogger(logger) {
91
+ this.setLogger(logger);
92
+ return this;
93
+ }
94
+ /**
95
+ * Set the logger instance
96
+ * @param logger A logger instance that implements the ConsoleLike interface
97
+ */
98
+ setLogger(logger) {
99
+ this.logger = logger;
100
+ }
101
+ /**
102
+ * Get all available audio input devices
103
+ * @param options Optional settings to force refresh the device list. Can include a refresh flag.
104
+ * @returns Promise resolving to an array of audio devices conforming to AudioDevice interface
105
+ */
106
+ async getAvailableDevices(options) {
107
+ try {
108
+ if (Platform.OS === 'web') {
109
+ this.availableDevices = await this.getWebAudioDevices();
110
+ }
111
+ else if (ExpoAudioStreamModule.getAvailableInputDevices) {
112
+ // Expecting an array of raw device objects from native
113
+ const rawDevices = await ExpoAudioStreamModule.getAvailableInputDevices(options);
114
+ // Map raw objects to the AudioDevice interface
115
+ this.availableDevices = rawDevices.map(mapRawDeviceToAudioDevice);
116
+ }
117
+ else {
118
+ // Fallback for unsupported platforms
119
+ this.availableDevices = [DEFAULT_DEVICE];
120
+ }
121
+ return this.availableDevices;
122
+ }
123
+ catch (error) {
124
+ this.logger?.error('Failed to get available devices:', error);
125
+ this.availableDevices = [DEFAULT_DEVICE]; // Ensure state is updated on error
126
+ return this.availableDevices;
127
+ }
128
+ }
129
+ /**
130
+ * Get the currently selected audio input device
131
+ * @returns Promise resolving to the current device (conforming to AudioDevice) or null
132
+ */
133
+ async getCurrentDevice() {
134
+ try {
135
+ if (Platform.OS === 'web') {
136
+ if (!this.currentDeviceId) {
137
+ // On web, return the typed default device if nothing is selected
138
+ return DEFAULT_DEVICE;
139
+ }
140
+ // Refresh web devices to ensure the current one is up-to-date
141
+ const webDevices = await this.getWebAudioDevices();
142
+ return (webDevices.find((d) => d.id === this.currentDeviceId) ||
143
+ DEFAULT_DEVICE // Fallback to default if current ID not found
144
+ );
145
+ }
146
+ else if (ExpoAudioStreamModule.getCurrentInputDevice) {
147
+ // Expecting a single raw device object or null from native
148
+ const rawDevice = await ExpoAudioStreamModule.getCurrentInputDevice();
149
+ // Map to AudioDevice interface if not null
150
+ return rawDevice ? mapRawDeviceToAudioDevice(rawDevice) : null;
151
+ }
152
+ else {
153
+ // Fallback for unsupported platforms
154
+ return DEFAULT_DEVICE;
155
+ }
156
+ }
157
+ catch (error) {
158
+ this.logger?.error('Failed to get current device:', error);
159
+ return DEFAULT_DEVICE; // Return default on error
160
+ }
161
+ }
162
+ /**
163
+ * Select a specific audio input device for recording
164
+ * @param deviceId The ID of the device to select
165
+ * @returns Promise resolving to a boolean indicating success
166
+ */
167
+ async selectDevice(deviceId) {
168
+ try {
169
+ let success = false;
170
+ if (Platform.OS === 'web') {
171
+ // Check if the device exists before setting it
172
+ const devices = await this.getWebAudioDevices();
173
+ if (devices.some((d) => d.id === deviceId)) {
174
+ this.currentDeviceId = deviceId;
175
+ success = true;
176
+ }
177
+ else {
178
+ this.logger?.warn(`Web: Device with ID ${deviceId} not found.`);
179
+ success = false;
180
+ }
181
+ }
182
+ else if (ExpoAudioStreamModule.selectInputDevice) {
183
+ success =
184
+ await ExpoAudioStreamModule.selectInputDevice(deviceId);
185
+ if (success) {
186
+ this.currentDeviceId = deviceId;
187
+ }
188
+ }
189
+ // Refresh devices after selection attempt to update state
190
+ await this.refreshDevices();
191
+ return success;
192
+ }
193
+ catch (error) {
194
+ this.logger?.error('Failed to select device:', error);
195
+ await this.refreshDevices(); // Refresh even on error
196
+ return false;
197
+ }
198
+ }
199
+ /**
200
+ * Reset to the default audio input device
201
+ * @returns Promise resolving to a boolean indicating success
202
+ */
203
+ async resetToDefaultDevice() {
204
+ try {
205
+ let success = false;
206
+ if (Platform.OS === 'web') {
207
+ this.currentDeviceId = 'default';
208
+ success = true;
209
+ }
210
+ else if (ExpoAudioStreamModule.resetToDefaultDevice) {
211
+ success = await ExpoAudioStreamModule.resetToDefaultDevice();
212
+ if (success) {
213
+ this.currentDeviceId = null;
214
+ }
215
+ }
216
+ // Refresh devices after reset attempt
217
+ await this.refreshDevices();
218
+ return success;
219
+ }
220
+ catch (error) {
221
+ this.logger?.error('Failed to reset to default device:', error);
222
+ await this.refreshDevices(); // Refresh even on error
223
+ return false;
224
+ }
225
+ }
226
+ /**
227
+ * Register a listener for device changes
228
+ * @param listener Function to call when devices change (receives AudioDevice[])
229
+ * @returns Function to remove the listener
230
+ */
231
+ addDeviceChangeListener(listener) {
232
+ this.deviceChangeListeners.add(listener);
233
+ // Immediately call listener with current devices if available
234
+ if (this.availableDevices.length > 0) {
235
+ listener([...this.availableDevices]);
236
+ }
237
+ // Return a function to remove the listener
238
+ return () => {
239
+ this.deviceChangeListeners.delete(listener);
240
+ };
241
+ }
242
+ /**
243
+ * Refresh the list of available devices with debouncing and notify listeners.
244
+ * @returns Promise resolving to the updated device list (AudioDevice[])
245
+ */
246
+ async refreshDevices() {
247
+ const now = Date.now();
248
+ if (this.refreshInProgress) {
249
+ this.logger?.debug('Refresh already in progress, skipping');
250
+ return this.availableDevices;
251
+ }
252
+ // Always allow refresh if forced by native event or longer than 2s debounce
253
+ const timeSinceLastRefresh = now - this.lastRefreshTime;
254
+ const shouldDebounce = timeSinceLastRefresh < this.refreshDebounceMs &&
255
+ timeSinceLastRefresh < 2000;
256
+ if (shouldDebounce) {
257
+ this.logger?.debug(`Refresh debounced, skipping (last refresh was ${timeSinceLastRefresh}ms ago)`);
258
+ return this.availableDevices;
259
+ }
260
+ this.logger?.debug('Refreshing devices...');
261
+ this.refreshInProgress = true;
262
+ try {
263
+ // Fetch the latest devices; getAvailableDevices handles mapping now
264
+ const devices = await this.getAvailableDevices({ refresh: true });
265
+ // availableDevices state is updated within getAvailableDevices
266
+ this.notifyListeners(); // Notify listeners with the updated list
267
+ this.lastRefreshTime = Date.now();
268
+ return devices; // Return the fetched & mapped list
269
+ }
270
+ catch (error) {
271
+ this.logger?.error('Error during refreshDevices:', error);
272
+ return this.availableDevices; // Return potentially stale list on error
273
+ }
274
+ finally {
275
+ this.refreshInProgress = false;
276
+ this.logger?.debug('Refresh finished.');
277
+ }
278
+ }
279
+ /**
280
+ * Get audio input devices using the Web Audio API
281
+ * @returns Promise resolving to an array of AudioDevice objects
282
+ */
283
+ async getWebAudioDevices() {
284
+ if (typeof navigator === 'undefined' ||
285
+ !navigator.mediaDevices ||
286
+ !navigator.mediaDevices.enumerateDevices) {
287
+ return [DEFAULT_DEVICE];
288
+ }
289
+ try {
290
+ const permissionStatus = await this.checkMicrophonePermission();
291
+ if (permissionStatus === 'denied') {
292
+ return [
293
+ {
294
+ ...DEFAULT_DEVICE,
295
+ name: 'Microphone Access Denied',
296
+ isAvailable: false,
297
+ },
298
+ ];
299
+ }
300
+ if (permissionStatus !== 'granted') {
301
+ try {
302
+ // Requesting stream often reveals device labels
303
+ await navigator.mediaDevices.getUserMedia({ audio: true });
304
+ }
305
+ catch (error) {
306
+ this.logger?.warn('Microphone permission request failed:', error);
307
+ return [
308
+ {
309
+ ...DEFAULT_DEVICE,
310
+ name: 'Microphone Access Required',
311
+ isAvailable: false,
312
+ },
313
+ ];
314
+ }
315
+ }
316
+ const devices = await navigator.mediaDevices.enumerateDevices();
317
+ const audioInputDevices = devices
318
+ .filter((device) => device.kind === 'audioinput')
319
+ .map((device) => this.mapWebDeviceToAudioDevice(device));
320
+ const hasUnlabeledDevices = audioInputDevices.some((device) => !device.name || device.name.startsWith('Microphone '));
321
+ let finalDevices = audioInputDevices;
322
+ if (hasUnlabeledDevices && this.isSafariOrIOS()) {
323
+ finalDevices = this.enhanceDevicesForSafari(audioInputDevices);
324
+ }
325
+ if (finalDevices.length === 0) {
326
+ finalDevices = [DEFAULT_DEVICE];
327
+ }
328
+ this.setupWebDeviceChangeListener();
329
+ this.availableDevices = finalDevices; // Update internal state
330
+ return finalDevices;
331
+ }
332
+ catch (error) {
333
+ this.logger?.error('Failed to enumerate web audio devices:', error);
334
+ this.availableDevices = [DEFAULT_DEVICE]; // Update state on error
335
+ return this.availableDevices;
336
+ }
337
+ }
338
+ /**
339
+ * Check the current microphone permission status
340
+ * @returns Permission state ('prompt', 'granted', or 'denied')
341
+ */
342
+ async checkMicrophonePermission() {
343
+ if (!navigator.permissions || !navigator.permissions.query) {
344
+ return 'prompt';
345
+ }
346
+ try {
347
+ const permissionStatus = await navigator.permissions.query({
348
+ name: 'microphone',
349
+ });
350
+ permissionStatus.onchange = () => {
351
+ // Refresh devices when permission changes
352
+ this.refreshDevices();
353
+ };
354
+ return permissionStatus.state;
355
+ }
356
+ catch (error) {
357
+ this.logger?.warn('Permission query not supported:', error);
358
+ return 'prompt';
359
+ }
360
+ }
361
+ /**
362
+ * Setup listener for device changes in web environment
363
+ */
364
+ setupWebDeviceChangeListener() {
365
+ if (typeof navigator === 'undefined' ||
366
+ !navigator.mediaDevices ||
367
+ this.deviceListeners.size > 0 // Avoid adding multiple listeners
368
+ ) {
369
+ return;
370
+ }
371
+ const handleDeviceChange = () => {
372
+ this.logger?.debug('Web device change detected.');
373
+ // Refresh devices on change
374
+ this.refreshDevices();
375
+ };
376
+ navigator.mediaDevices.addEventListener('devicechange', handleDeviceChange);
377
+ this.deviceListeners.add(handleDeviceChange);
378
+ this.logger?.debug('Web device change listener added.');
379
+ }
380
+ /**
381
+ * Check if the current browser is Safari or iOS WebKit
382
+ */
383
+ isSafariOrIOS() {
384
+ if (typeof navigator === 'undefined')
385
+ return false;
386
+ const ua = navigator.userAgent;
387
+ return (/^((?!chrome|android).)*safari/i.test(ua) ||
388
+ /iPad|iPhone|iPod/.test(ua) ||
389
+ (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1));
390
+ }
391
+ /**
392
+ * Create enhanced device information for Safari and privacy-restricted browsers
393
+ * @param devices Array of AudioDevice objects, potentially unlabeled
394
+ * @returns Array of enhanced AudioDevice objects
395
+ */
396
+ enhanceDevicesForSafari(devices) {
397
+ const defaultDevice = devices.find((d) => d.isDefault);
398
+ if (devices.length <= 1) {
399
+ // Return a typed default device
400
+ return [
401
+ {
402
+ id: defaultDevice?.id || 'default',
403
+ name: 'Microphone (Browser Managed)',
404
+ type: 'builtin_mic',
405
+ isDefault: true,
406
+ isAvailable: true,
407
+ capabilities: defaultDevice?.capabilities ||
408
+ DEFAULT_DEVICE.capabilities,
409
+ },
410
+ ];
411
+ }
412
+ // Provide more descriptive names for unlabeled devices
413
+ return devices.map((device, index) => {
414
+ if (!device.name || device.name.startsWith('Microphone ')) {
415
+ const deviceTypes = [
416
+ 'Built-in Microphone',
417
+ 'External Microphone',
418
+ 'Headset Microphone',
419
+ ];
420
+ const typeName = deviceTypes[index % deviceTypes.length];
421
+ return {
422
+ ...device,
423
+ name: device.isDefault ? `${typeName} (Default)` : typeName,
424
+ };
425
+ }
426
+ return device;
427
+ });
428
+ }
429
+ /**
430
+ * Map a Web MediaDeviceInfo to our AudioDevice format
431
+ * @param device The MediaDeviceInfo object from the browser
432
+ * @returns An object conforming to the AudioDevice interface
433
+ */
434
+ mapWebDeviceToAudioDevice(device) {
435
+ const isDefault = device.deviceId === 'default';
436
+ const deviceType = this.inferDeviceType(device.label || '');
437
+ // Provide reasonable default capabilities for web devices
438
+ const defaultWebCapabilities = {
439
+ sampleRates: [16000, 44100, 48000],
440
+ channelCounts: [1, 2],
441
+ bitDepths: [16, 32], // Web Audio uses float32, common PCM might be 16/32
442
+ hasEchoCancellation: true, // Often handled by browser
443
+ hasNoiseSuppression: true, // Often handled by browser
444
+ hasAutomaticGainControl: true, // Often handled by browser
445
+ };
446
+ return {
447
+ id: device.deviceId,
448
+ name: device.label || `Microphone ${device.deviceId.substring(0, 8)}`,
449
+ type: deviceType,
450
+ isDefault,
451
+ isAvailable: true, // Assume available if enumerated
452
+ capabilities: defaultWebCapabilities,
453
+ };
454
+ }
455
+ /**
456
+ * Try to infer the device type from its name
457
+ * @param deviceName The label of the device
458
+ * @returns A string representing the inferred device type
459
+ */
460
+ inferDeviceType(deviceName) {
461
+ const name = deviceName.toLowerCase();
462
+ if (name.includes('bluetooth') || name.includes('airpods'))
463
+ return 'bluetooth';
464
+ if (name.includes('usb'))
465
+ return 'usb';
466
+ if (name.includes('headphone') || name.includes('headset')) {
467
+ return name.includes('wired') ? 'wired_headset' : 'wired_headphones';
468
+ }
469
+ if (name.includes('speaker'))
470
+ return 'speaker';
471
+ return 'builtin_mic'; // Default assumption
472
+ }
473
+ /**
474
+ * Notify all registered listeners about device changes.
475
+ */
476
+ notifyListeners() {
477
+ // Pass a copy of the current devices array to listeners
478
+ const devicesCopy = [...this.availableDevices];
479
+ this.logger?.debug(`Notifying ${this.deviceChangeListeners.size} listeners with ${devicesCopy.length} devices.`);
480
+ this.deviceChangeListeners.forEach((listener) => {
481
+ try {
482
+ listener(devicesCopy);
483
+ }
484
+ catch (error) {
485
+ this.logger?.error('Error in device change listener:', error);
486
+ }
487
+ });
488
+ }
489
+ }
490
+ // Create and export the singleton instance
491
+ export const audioDeviceManager = new AudioDeviceManager();
492
+ export { DeviceDisconnectionBehavior };
493
+ //# sourceMappingURL=AudioDeviceManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AudioDeviceManager.js","sourceRoot":"","sources":["../src/AudioDeviceManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAEvC,OAAO,EAGH,2BAA2B,GAE9B,MAAM,yBAAyB,CAAA;AAChC,OAAO,qBAAqB,MAAM,yBAAyB,CAAA;AAE3D,4DAA4D;AAC5D,MAAM,cAAc,GAAgB;IAChC,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,oBAAoB;IAC1B,IAAI,EAAE,aAAa;IACnB,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,IAAI;IACjB,YAAY,EAAE;QACV,WAAW,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC;QAClC,aAAa,EA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A;AAE1D,OAAO,EAAE,2BAA2B,EAAE,CAAA","sourcesContent":["import { EventEmitter } from 'expo-modules-core'\nimport { Platform } from 'react-native'\n\nimport {\n AudioDevice,\n AudioDeviceCapabilities,\n DeviceDisconnectionBehavior,\n ConsoleLike,\n} from './ExpoAudioStream.types'\nimport ExpoAudioStreamModule from './ExpoAudioStreamModule'\n\n// Default device fallback for web and unsupported platforms\nconst DEFAULT_DEVICE: AudioDevice = {\n id: 'default',\n name: 'Default Microphone',\n type: 'builtin_mic',\n isDefault: true,\n isAvailable: true,\n capabilities: {\n sampleRates: [16000, 44100, 48000],\n channelCounts: [1, 2],\n bitDepths: [16, 24, 32],\n hasEchoCancellation: true,\n hasNoiseSuppression: true,\n hasAutomaticGainControl: true,\n },\n}\n\n// Helper function to map raw object to AudioDevice interface\n// This handles potential inconsistencies from the native module\nfunction mapRawDeviceToAudioDevice(rawDevice: any): AudioDevice {\n const capabilities = rawDevice.capabilities || {}\n return {\n id: rawDevice.id || 'unknown',\n name: rawDevice.name || 'Unknown Device',\n type: rawDevice.type || 'unknown',\n isDefault: rawDevice.isDefault || false,\n isAvailable:\n rawDevice.isAvailable !== undefined ? rawDevice.isAvailable : true, // Default to true if undefined\n capabilities: {\n sampleRates: capabilities.sampleRates || [16000, 44100, 48000], // Provide defaults\n channelCounts: capabilities.channelCounts || [1, 2],\n bitDepths: capabilities.bitDepths || [16, 24, 32],\n hasEchoCancellation: capabilities.hasEchoCancellation,\n hasNoiseSuppression: capabilities.hasNoiseSuppression,\n hasAutomaticGainControl: capabilities.hasAutomaticGainControl,\n },\n }\n}\n\n/**\n * Class that provides a cross-platform API for managing audio input devices\n */\nexport class AudioDeviceManager {\n private eventEmitter: InstanceType<typeof EventEmitter>\n private currentDeviceId: string | null = null\n private availableDevices: AudioDevice[] = []\n private deviceChangeListeners: Set<(devices: AudioDevice[]) => void> =\n new Set()\n private deviceListeners: Set<() => void> = new Set()\n private lastRefreshTime: number = 0\n private refreshInProgress: boolean = false\n private refreshDebounceMs: number = 500 // Minimum 500ms between refreshes\n private logger?: ConsoleLike\n\n constructor(options?: { logger?: ConsoleLike }) {\n this.eventEmitter = new EventEmitter(ExpoAudioStreamModule)\n this.logger = options?.logger\n\n // Listen for device change events from native modules if not on web\n if (Platform.OS !== 'web') {\n // Store the last event type to avoid duplicates\n let lastEventType: string | null = null\n let lastEventTime = 0\n\n this.eventEmitter.addListener(\n 'deviceChangedEvent',\n (event: any) => {\n // Skip processing duplicate events that occur too close together\n const now = Date.now()\n const isSimilarEvent =\n lastEventType === event.type &&\n now - lastEventTime < this.refreshDebounceMs\n\n if (isSimilarEvent) {\n this.logger?.debug(\n `Skipping similar device event (${event.type}) received too soon`\n )\n return\n }\n\n // Update the last event tracking\n lastEventType = event.type\n lastEventTime = now\n\n // Only refresh on meaningful events\n if (\n event.type === 'deviceConnected' ||\n event.type === 'deviceDisconnected' ||\n event.type === 'routeChanged'\n ) {\n this.logger?.debug(\n `Processing device event: ${event.type}`\n )\n // Refresh devices and notify listeners regardless of the direct return value\n this.refreshDevices()\n }\n }\n )\n }\n }\n\n /**\n * Initialize the device manager with a logger\n * @param logger A logger instance that implements the ConsoleLike interface\n * @returns The manager instance for chaining\n */\n initWithLogger(logger: ConsoleLike): AudioDeviceManager {\n this.setLogger(logger)\n return this\n }\n\n /**\n * Set the logger instance\n * @param logger A logger instance that implements the ConsoleLike interface\n */\n setLogger(logger: ConsoleLike) {\n this.logger = logger\n }\n\n /**\n * Get all available audio input devices\n * @param options Optional settings to force refresh the device list. Can include a refresh flag.\n * @returns Promise resolving to an array of audio devices conforming to AudioDevice interface\n */\n async getAvailableDevices(options?: {\n refresh?: boolean\n }): Promise<AudioDevice[]> {\n try {\n if (Platform.OS === 'web') {\n this.availableDevices = await this.getWebAudioDevices()\n } else if (ExpoAudioStreamModule.getAvailableInputDevices) {\n // Expecting an array of raw device objects from native\n const rawDevices: any[] =\n await ExpoAudioStreamModule.getAvailableInputDevices(\n options\n )\n // Map raw objects to the AudioDevice interface\n this.availableDevices = rawDevices.map(\n mapRawDeviceToAudioDevice\n )\n } else {\n // Fallback for unsupported platforms\n this.availableDevices = [DEFAULT_DEVICE]\n }\n return this.availableDevices\n } catch (error) {\n this.logger?.error('Failed to get available devices:', error)\n this.availableDevices = [DEFAULT_DEVICE] // Ensure state is updated on error\n return this.availableDevices\n }\n }\n\n /**\n * Get the currently selected audio input device\n * @returns Promise resolving to the current device (conforming to AudioDevice) or null\n */\n async getCurrentDevice(): Promise<AudioDevice | null> {\n try {\n if (Platform.OS === 'web') {\n if (!this.currentDeviceId) {\n // On web, return the typed default device if nothing is selected\n return DEFAULT_DEVICE\n }\n // Refresh web devices to ensure the current one is up-to-date\n const webDevices = await this.getWebAudioDevices()\n return (\n webDevices.find((d) => d.id === this.currentDeviceId) ||\n DEFAULT_DEVICE // Fallback to default if current ID not found\n )\n } else if (ExpoAudioStreamModule.getCurrentInputDevice) {\n // Expecting a single raw device object or null from native\n const rawDevice: any | null =\n await ExpoAudioStreamModule.getCurrentInputDevice()\n // Map to AudioDevice interface if not null\n return rawDevice ? mapRawDeviceToAudioDevice(rawDevice) : null\n } else {\n // Fallback for unsupported platforms\n return DEFAULT_DEVICE\n }\n } catch (error) {\n this.logger?.error('Failed to get current device:', error)\n return DEFAULT_DEVICE // Return default on error\n }\n }\n\n /**\n * Select a specific audio input device for recording\n * @param deviceId The ID of the device to select\n * @returns Promise resolving to a boolean indicating success\n */\n async selectDevice(deviceId: string): Promise<boolean> {\n try {\n let success = false\n if (Platform.OS === 'web') {\n // Check if the device exists before setting it\n const devices = await this.getWebAudioDevices()\n if (devices.some((d) => d.id === deviceId)) {\n this.currentDeviceId = deviceId\n success = true\n } else {\n this.logger?.warn(\n `Web: Device with ID ${deviceId} not found.`\n )\n success = false\n }\n } else if (ExpoAudioStreamModule.selectInputDevice) {\n success =\n await ExpoAudioStreamModule.selectInputDevice(deviceId)\n if (success) {\n this.currentDeviceId = deviceId\n }\n }\n // Refresh devices after selection attempt to update state\n await this.refreshDevices()\n return success\n } catch (error) {\n this.logger?.error('Failed to select device:', error)\n await this.refreshDevices() // Refresh even on error\n return false\n }\n }\n\n /**\n * Reset to the default audio input device\n * @returns Promise resolving to a boolean indicating success\n */\n async resetToDefaultDevice(): Promise<boolean> {\n try {\n let success = false\n if (Platform.OS === 'web') {\n this.currentDeviceId = 'default'\n success = true\n } else if (ExpoAudioStreamModule.resetToDefaultDevice) {\n success = await ExpoAudioStreamModule.resetToDefaultDevice()\n if (success) {\n this.currentDeviceId = null\n }\n }\n // Refresh devices after reset attempt\n await this.refreshDevices()\n return success\n } catch (error) {\n this.logger?.error('Failed to reset to default device:', error)\n await this.refreshDevices() // Refresh even on error\n return false\n }\n }\n\n /**\n * Register a listener for device changes\n * @param listener Function to call when devices change (receives AudioDevice[])\n * @returns Function to remove the listener\n */\n addDeviceChangeListener(\n listener: (devices: AudioDevice[]) => void\n ): () => void {\n this.deviceChangeListeners.add(listener)\n\n // Immediately call listener with current devices if available\n if (this.availableDevices.length > 0) {\n listener([...this.availableDevices])\n }\n\n // Return a function to remove the listener\n return () => {\n this.deviceChangeListeners.delete(listener)\n }\n }\n\n /**\n * Refresh the list of available devices with debouncing and notify listeners.\n * @returns Promise resolving to the updated device list (AudioDevice[])\n */\n async refreshDevices(): Promise<AudioDevice[]> {\n const now = Date.now()\n\n if (this.refreshInProgress) {\n this.logger?.debug('Refresh already in progress, skipping')\n return this.availableDevices\n }\n\n // Always allow refresh if forced by native event or longer than 2s debounce\n const timeSinceLastRefresh = now - this.lastRefreshTime\n const shouldDebounce =\n timeSinceLastRefresh < this.refreshDebounceMs &&\n timeSinceLastRefresh < 2000\n\n if (shouldDebounce) {\n this.logger?.debug(\n `Refresh debounced, skipping (last refresh was ${timeSinceLastRefresh}ms ago)`\n )\n return this.availableDevices\n }\n\n this.logger?.debug('Refreshing devices...')\n this.refreshInProgress = true\n try {\n // Fetch the latest devices; getAvailableDevices handles mapping now\n const devices = await this.getAvailableDevices({ refresh: true })\n // availableDevices state is updated within getAvailableDevices\n this.notifyListeners() // Notify listeners with the updated list\n this.lastRefreshTime = Date.now()\n return devices // Return the fetched & mapped list\n } catch (error) {\n this.logger?.error('Error during refreshDevices:', error)\n return this.availableDevices // Return potentially stale list on error\n } finally {\n this.refreshInProgress = false\n this.logger?.debug('Refresh finished.')\n }\n }\n\n /**\n * Get audio input devices using the Web Audio API\n * @returns Promise resolving to an array of AudioDevice objects\n */\n private async getWebAudioDevices(): Promise<AudioDevice[]> {\n if (\n typeof navigator === 'undefined' ||\n !navigator.mediaDevices ||\n !navigator.mediaDevices.enumerateDevices\n ) {\n return [DEFAULT_DEVICE]\n }\n\n try {\n const permissionStatus = await this.checkMicrophonePermission()\n\n if (permissionStatus === 'denied') {\n return [\n {\n ...DEFAULT_DEVICE,\n name: 'Microphone Access Denied',\n isAvailable: false,\n },\n ]\n }\n\n if (permissionStatus !== 'granted') {\n try {\n // Requesting stream often reveals device labels\n await navigator.mediaDevices.getUserMedia({ audio: true })\n } catch (error) {\n this.logger?.warn(\n 'Microphone permission request failed:',\n error\n )\n return [\n {\n ...DEFAULT_DEVICE,\n name: 'Microphone Access Required',\n isAvailable: false,\n },\n ]\n }\n }\n\n const devices = await navigator.mediaDevices.enumerateDevices()\n const audioInputDevices = devices\n .filter((device) => device.kind === 'audioinput')\n .map((device) => this.mapWebDeviceToAudioDevice(device))\n\n const hasUnlabeledDevices = audioInputDevices.some(\n (device) =>\n !device.name || device.name.startsWith('Microphone ')\n )\n\n let finalDevices = audioInputDevices\n if (hasUnlabeledDevices && this.isSafariOrIOS()) {\n finalDevices = this.enhanceDevicesForSafari(audioInputDevices)\n }\n\n if (finalDevices.length === 0) {\n finalDevices = [DEFAULT_DEVICE]\n }\n\n this.setupWebDeviceChangeListener()\n this.availableDevices = finalDevices // Update internal state\n return finalDevices\n } catch (error) {\n this.logger?.error('Failed to enumerate web audio devices:', error)\n this.availableDevices = [DEFAULT_DEVICE] // Update state on error\n return this.availableDevices\n }\n }\n\n /**\n * Check the current microphone permission status\n * @returns Permission state ('prompt', 'granted', or 'denied')\n */\n private async checkMicrophonePermission(): Promise<PermissionState> {\n if (!navigator.permissions || !navigator.permissions.query) {\n return 'prompt'\n }\n try {\n const permissionStatus = await navigator.permissions.query({\n name: 'microphone' as PermissionName,\n })\n permissionStatus.onchange = () => {\n // Refresh devices when permission changes\n this.refreshDevices()\n }\n return permissionStatus.state\n } catch (error) {\n this.logger?.warn('Permission query not supported:', error)\n return 'prompt'\n }\n }\n\n /**\n * Setup listener for device changes in web environment\n */\n private setupWebDeviceChangeListener() {\n if (\n typeof navigator === 'undefined' ||\n !navigator.mediaDevices ||\n this.deviceListeners.size > 0 // Avoid adding multiple listeners\n ) {\n return\n }\n\n const handleDeviceChange = () => {\n this.logger?.debug('Web device change detected.')\n // Refresh devices on change\n this.refreshDevices()\n }\n\n navigator.mediaDevices.addEventListener(\n 'devicechange',\n handleDeviceChange\n )\n this.deviceListeners.add(handleDeviceChange)\n this.logger?.debug('Web device change listener added.')\n }\n\n /**\n * Check if the current browser is Safari or iOS WebKit\n */\n private isSafariOrIOS(): boolean {\n if (typeof navigator === 'undefined') return false\n const ua = navigator.userAgent\n return (\n /^((?!chrome|android).)*safari/i.test(ua) ||\n /iPad|iPhone|iPod/.test(ua) ||\n (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)\n )\n }\n\n /**\n * Create enhanced device information for Safari and privacy-restricted browsers\n * @param devices Array of AudioDevice objects, potentially unlabeled\n * @returns Array of enhanced AudioDevice objects\n */\n private enhanceDevicesForSafari(devices: AudioDevice[]): AudioDevice[] {\n const defaultDevice = devices.find((d) => d.isDefault)\n\n if (devices.length <= 1) {\n // Return a typed default device\n return [\n {\n id: defaultDevice?.id || 'default',\n name: 'Microphone (Browser Managed)',\n type: 'builtin_mic',\n isDefault: true,\n isAvailable: true,\n capabilities:\n defaultDevice?.capabilities ||\n DEFAULT_DEVICE.capabilities,\n },\n ]\n }\n\n // Provide more descriptive names for unlabeled devices\n return devices.map((device, index) => {\n if (!device.name || device.name.startsWith('Microphone ')) {\n const deviceTypes = [\n 'Built-in Microphone',\n 'External Microphone',\n 'Headset Microphone',\n ]\n const typeName = deviceTypes[index % deviceTypes.length]\n return {\n ...device,\n name: device.isDefault ? `${typeName} (Default)` : typeName,\n }\n }\n return device\n })\n }\n\n /**\n * Map a Web MediaDeviceInfo to our AudioDevice format\n * @param device The MediaDeviceInfo object from the browser\n * @returns An object conforming to the AudioDevice interface\n */\n private mapWebDeviceToAudioDevice(device: MediaDeviceInfo): AudioDevice {\n const isDefault = device.deviceId === 'default'\n const deviceType = this.inferDeviceType(device.label || '')\n\n // Provide reasonable default capabilities for web devices\n const defaultWebCapabilities: AudioDeviceCapabilities = {\n sampleRates: [16000, 44100, 48000],\n channelCounts: [1, 2],\n bitDepths: [16, 32], // Web Audio uses float32, common PCM might be 16/32\n hasEchoCancellation: true, // Often handled by browser\n hasNoiseSuppression: true, // Often handled by browser\n hasAutomaticGainControl: true, // Often handled by browser\n }\n\n return {\n id: device.deviceId,\n name:\n device.label || `Microphone ${device.deviceId.substring(0, 8)}`,\n type: deviceType,\n isDefault,\n isAvailable: true, // Assume available if enumerated\n capabilities: defaultWebCapabilities,\n }\n }\n\n /**\n * Try to infer the device type from its name\n * @param deviceName The label of the device\n * @returns A string representing the inferred device type\n */\n private inferDeviceType(deviceName: string): string {\n const name = deviceName.toLowerCase()\n if (name.includes('bluetooth') || name.includes('airpods'))\n return 'bluetooth'\n if (name.includes('usb')) return 'usb'\n if (name.includes('headphone') || name.includes('headset')) {\n return name.includes('wired') ? 'wired_headset' : 'wired_headphones'\n }\n if (name.includes('speaker')) return 'speaker'\n return 'builtin_mic' // Default assumption\n }\n\n /**\n * Notify all registered listeners about device changes.\n */\n private notifyListeners(): void {\n // Pass a copy of the current devices array to listeners\n const devicesCopy = [...this.availableDevices]\n this.logger?.debug(\n `Notifying ${this.deviceChangeListeners.size} listeners with ${devicesCopy.length} devices.`\n )\n this.deviceChangeListeners.forEach((listener) => {\n try {\n listener(devicesCopy)\n } catch (error) {\n this.logger?.error('Error in device change listener:', error)\n }\n })\n }\n}\n\n// Create and export the singleton instance\nexport const audioDeviceManager = new AudioDeviceManager()\n\nexport { DeviceDisconnectionBehavior }\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"AudioRecorder.provider.d.ts","sourceRoot":"","sources":["../src/AudioRecorder.provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAoC,MAAM,OAAO,CAAA;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAC/D,OAAO,EAAE,qBAAqB,EAAoB,MAAM,oBAAoB,CAAA;AAwB5E,UAAU,0BAA0B;IAChC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;IACzB,MAAM,CAAC,EAAE,qBAAqB,CAAA;CACjC;AAED,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAUtE,CAAA;AAED,eAAO,MAAM,sBAAsB,6BAQlC,CAAA"}
1
+ {"version":3,"file":"AudioRecorder.provider.d.ts","sourceRoot":"","sources":["../src/AudioRecorder.provider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAoC,MAAM,OAAO,CAAA;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAC/D,OAAO,EAAE,qBAAqB,EAAoB,MAAM,oBAAoB,CAAA;AA2B5E,UAAU,0BAA0B;IAChC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;IACzB,MAAM,CAAC,EAAE,qBAAqB,CAAA;CACjC;AAED,eAAO,MAAM,qBAAqB,EAAE,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAUtE,CAAA;AAED,eAAO,MAAM,sBAAsB,6BAQlC,CAAA"}
@@ -19,6 +19,9 @@ const initContext = {
19
19
  resumeRecording: async () => {
20
20
  throw new Error('AudioRecorderProvider not found');
21
21
  },
22
+ prepareRecording: async () => {
23
+ throw new Error('AudioRecorderProvider not found');
24
+ },
22
25
  };
23
26
  const AudioRecorderContext = createContext(initContext);
24
27
  export const AudioRecorderProvider = ({ children, config = {}, }) => {
@@ -1 +1 @@
1
- {"version":3,"file":"AudioRecorder.provider.js","sourceRoot":"","sources":["../src/AudioRecorder.provider.tsx"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,OAAO,KAAK,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAA;AAGxD,OAAO,EAAyB,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAE5E,MAAM,WAAW,GAA0B;IACvC,WAAW,EAAE,KAAK;IAClB,QAAQ,EAAE,KAAK;IACf,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IACP,WAAW,EAAE,SAAS;IACtB,cAAc,EAAE,KAAK,IAAI,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;IACtD,CAAC;IACD,aAAa,EAAE,KAAK,IAAI,EAAE;QACtB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;IACtD,CAAC;IACD,cAAc,EAAE,KAAK,IAAI,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;IACtD,CAAC;IACD,eAAe,EAAE,KAAK,IAAI,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAA;IACtD,CAAC;CACJ,CAAA;AAED,MAAM,oBAAoB,GAAG,aAAa,CAAwB,WAAW,CAAC,CAAA;AAO9E,MAAM,CAAC,MAAM,qBAAqB,GAAyC,CAAC,EACxE,QAAQ,EACR,MAAM,GAAG,EAAE,GACd,EAAE,EAAE;IACD,MAAM,aAAa,GAAG,gBAAgB,CAAC,MAAM,CAAC,CAAA;IAC9C,OAAO,CACH,CAAC,oBAAoB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,aAAa,CAAC,CAChD;YAAA,CAAC,QAAQ,CACb;QAAA,EAAE,oBAAoB,CAAC,QAAQ,CAAC,CACnC,CAAA;AACL,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,GAAG,EAAE;IACvC,MAAM,OAAO,GAAG,UAAU,CAAC,oBAAoB,CAAC,CAAA;IAChD,IAAI,CAAC,OAAO,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACX,qEAAqE,CACxE,CAAA;IACL,CAAC;IACD,OAAO,OAAO,CAAA;AAClB,CAAC,CAAA","sourcesContent":["// packages/expo-audio-stream/src/AudioRecorder.provider.tsx\nimport React, { createContext, useContext } from 'react'\n\nimport { UseAudioRecorderState } from './ExpoAudioStream.types'\nimport { UseAudioRecorderProps, useAudioRecorder } from './useAudioRecorder'\n\nconst initContext: UseAudioRecorderState = {\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n startRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n stopRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n pauseRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n resumeRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n}\n\nconst AudioRecorderContext = createContext<UseAudioRecorderState>(initContext)\n\ninterface AudioRecorderProviderProps {\n children: React.ReactNode\n config?: UseAudioRecorderProps\n}\n\nexport const AudioRecorderProvider: React.FC<AudioRecorderProviderProps> = ({\n children,\n config = {},\n}) => {\n const audioRecorder = useAudioRecorder(config)\n return (\n <AudioRecorderContext.Provider value={audioRecorder}>\n {children}\n </AudioRecorderContext.Provider>\n )\n}\n\nexport const useSharedAudioRecorder = () => {\n const context = useContext(AudioRecorderContext)\n if (!context) {\n throw new Error(\n 'useSharedAudioRecorder must be used within an AudioRecorderProvider'\n )\n }\n return context\n}\n"]}
1
+ {"version":3,"file":"AudioRecorder.provider.js","sourceRoot":"","sources":["../src/AudioRecorder.provider.tsx"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,OAAO,KAAK,EAAE,EAAE,aAAa,EAAE,UAAU,EAAE,M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AC,OAAO,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACX,qEAAqE,CACxE,CAAA;IACL,CAAC;IACD,OAAO,OAAO,CAAA;AAClB,CAAC,CAAA","sourcesContent":["// packages/expo-audio-stream/src/AudioRecorder.provider.tsx\nimport React, { createContext, useContext } from 'react'\n\nimport { UseAudioRecorderState } from './ExpoAudioStream.types'\nimport { UseAudioRecorderProps, useAudioRecorder } from './useAudioRecorder'\n\nconst initContext: UseAudioRecorderState = {\n isRecording: false,\n isPaused: false,\n durationMs: 0,\n size: 0,\n compression: undefined,\n startRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n stopRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n pauseRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n resumeRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n prepareRecording: async () => {\n throw new Error('AudioRecorderProvider not found')\n },\n}\n\nconst AudioRecorderContext = createContext<UseAudioRecorderState>(initContext)\n\ninterface AudioRecorderProviderProps {\n children: React.ReactNode\n config?: UseAudioRecorderProps\n}\n\nexport const AudioRecorderProvider: React.FC<AudioRecorderProviderProps> = ({\n children,\n config = {},\n}) => {\n const audioRecorder = useAudioRecorder(config)\n return (\n <AudioRecorderContext.Provider value={audioRecorder}>\n {children}\n </AudioRecorderContext.Provider>\n )\n}\n\nexport const useSharedAudioRecorder = () => {\n const context = useContext(AudioRecorderContext)\n if (!context) {\n throw new Error(\n 'useSharedAudioRecorder must be used within an AudioRecorderProvider'\n )\n }\n return context\n}\n"]}