The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | diff --git a/android/src/main/java/expo/modules/audio/AudioModule.kt b/android/src/main/java/expo/modules/audio/AudioModule.kt |
| 2 | index 6c81fce3dd518d3b82e3280940a001c7be84dd0a..16125c679c870e2eae48f8db953dedd3fc842c3d 100644 |
| 3 | --- a/android/src/main/java/expo/modules/audio/AudioModule.kt |
| 4 | +++ b/android/src/main/java/expo/modules/audio/AudioModule.kt |
| 5 | @@ -677,7 +677,7 @@ class AudioModule : Module() { |
| 6 | } |
| 7 | } |
| 8 | |
| 9 | - Function("pause") { player: AudioPlayer -> |
| 10 | + Function("pause") { player: AudioPlayer, /* deactivateSession - iOS only */ _: Boolean? -> |
| 11 | runOnMain { |
| 12 | player.isPaused = false |
| 13 | player.ref.pause() |
| 14 | @@ -824,10 +824,14 @@ class AudioModule : Module() { |
| 15 | return@Function recorder.getAvailableInputs(audioManager) |
| 16 | } |
| 17 | |
| 18 | - Function("setInput") { recorder: AudioRecorder, input: String -> |
| 19 | + AsyncFunction("setInput") Coroutine { recorder: AudioRecorder, input: String -> |
| 20 | recorder.setInput(input, audioManager) |
| 21 | } |
| 22 | |
| 23 | + Function("cancelInputSelection") { recorder: AudioRecorder -> |
| 24 | + recorder.cancelInputSelection() |
| 25 | + } |
| 26 | + |
| 27 | Function("startRecordingAtTime") { recorder: AudioRecorder, seconds: Double -> |
| 28 | checkRecordingPermission() |
| 29 | if (recorder.isPrepared) { |
| 30 | diff --git a/android/src/main/java/expo/modules/audio/AudioRecorder.kt b/android/src/main/java/expo/modules/audio/AudioRecorder.kt |
| 31 | index 2ff4a474fdea3efa652436a8a3960c3669ad298b..1ced279991294d3d81cb20fa339ca73e5d6d6c01 100644 |
| 32 | --- a/android/src/main/java/expo/modules/audio/AudioRecorder.kt |
| 33 | +++ b/android/src/main/java/expo/modules/audio/AudioRecorder.kt |
| 34 | @@ -19,6 +19,9 @@ import expo.modules.kotlin.exception.CodedException |
| 35 | import expo.modules.kotlin.exception.Exceptions |
| 36 | import expo.modules.kotlin.sharedobjects.SharedObject |
| 37 | import kotlinx.coroutines.Job |
| 38 | +import kotlinx.coroutines.CancellationException |
| 39 | +import kotlinx.coroutines.currentCoroutineContext |
| 40 | +import kotlinx.coroutines.job |
| 41 | import kotlinx.coroutines.delay |
| 42 | import kotlinx.coroutines.launch |
| 43 | import java.io.File |
| 44 | @@ -42,12 +45,19 @@ class AudioRecorder( |
| 45 | var isPrepared = false |
| 46 | |
| 47 | private var recorder: MediaRecorder? = null |
| 48 | + private val inputRoute = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { |
| 49 | + RecordingInputRoute(context.getSystemService(Context.AUDIO_SERVICE) as AudioManager) |
| 50 | + } else { |
| 51 | + null |
| 52 | + } |
| 53 | val id = UUID.randomUUID().toString() |
| 54 | var startTime = 0L |
| 55 | var isRecording = false |
| 56 | var isPaused = false |
| 57 | private var isPausedBySystem = false |
| 58 | private var recordingTimerJob: Job? = null |
| 59 | + private var inputSelectionJob: Job? = null |
| 60 | + private var inputSelectionCanceled = false |
| 61 | private var durationLimitMillis: Long? = null |
| 62 | var useForegroundService = false |
| 63 | |
| 64 | @@ -90,6 +100,7 @@ class AudioRecorder( |
| 65 | throw AudioRecorderAlreadyPreparedException() |
| 66 | } |
| 67 | |
| 68 | + synchronized(this) { inputSelectionCanceled = false } |
| 69 | val recordingOptions = options ?: this.options |
| 70 | val mediaRecorder = createRecorder(recordingOptions) |
| 71 | recorder = mediaRecorder |
| 72 | @@ -245,10 +256,15 @@ class AudioRecorder( |
| 73 | } |
| 74 | |
| 75 | private fun reset() { |
| 76 | + cancelInputSelection() |
| 77 | recordingTimerJob?.cancel() |
| 78 | recordingTimerJob = null |
| 79 | |
| 80 | - recorder?.release() |
| 81 | + try { |
| 82 | + recorder?.release() |
| 83 | + } finally { |
| 84 | + inputRoute?.close() |
| 85 | + } |
| 86 | recorder = null |
| 87 | isRecording = false |
| 88 | isPaused = false |
| 89 | @@ -468,55 +484,68 @@ class AudioRecorder( |
| 90 | throw DeviceInfoNotFoundException() |
| 91 | } |
| 92 | |
| 93 | - return getMapFromDeviceInfo(deviceInfo) |
| 94 | + return getMapFromDeviceInfo(deviceInfo, recordingInputs(audioManager)) |
| 95 | } |
| 96 | |
| 97 | private fun hasRecordingPermissions() = |
| 98 | ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED |
| 99 | |
| 100 | - fun getAvailableInputs(audioManager: AudioManager) = |
| 101 | - audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS).mapNotNull { deviceInfo -> |
| 102 | - val type = deviceInfo.type |
| 103 | - if (type == AudioDeviceInfo.TYPE_BUILTIN_MIC || type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || type == AudioDeviceInfo.TYPE_WIRED_HEADSET) { |
| 104 | - getMapFromDeviceInfo(deviceInfo) |
| 105 | - } else { |
| 106 | - null |
| 107 | - } |
| 108 | + fun getAvailableInputs(audioManager: AudioManager): List<Bundle> { |
| 109 | + val inputs = recordingInputs(audioManager) |
| 110 | + return inputs.map { getMapFromDeviceInfo(it, inputs) } |
| 111 | + } |
| 112 | + |
| 113 | + suspend fun setInput(uid: String, audioManager: AudioManager) { |
| 114 | + val job = currentCoroutineContext().job |
| 115 | + synchronized(this) { |
| 116 | + if (inputSelectionCanceled) throw CancellationException("Input selection canceled") |
| 117 | + inputSelectionJob = job |
| 118 | + } |
| 119 | + try { |
| 120 | + setInputDevice(uid, audioManager) |
| 121 | + } finally { |
| 122 | + synchronized(this) { if (inputSelectionJob === job) inputSelectionJob = null } |
| 123 | } |
| 124 | + } |
| 125 | + |
| 126 | + fun cancelInputSelection() { |
| 127 | + val job = synchronized(this) { |
| 128 | + inputSelectionCanceled = true |
| 129 | + inputSelectionJob |
| 130 | + } |
| 131 | + job?.cancel() |
| 132 | + } |
| 133 | |
| 134 | @Suppress("DEPRECATION") |
| 135 | - fun setInput(uid: String, audioManager: AudioManager) { |
| 136 | - val deviceInfo: AudioDeviceInfo? = getDeviceInfoFromUid(uid, audioManager) |
| 137 | + private suspend fun setInputDevice(uid: String, audioManager: AudioManager) { |
| 138 | + val deviceInfo = getDeviceInfoFromUid(uid, audioManager) ?: throw PreferredInputNotFoundException() |
| 139 | |
| 140 | if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { |
| 141 | throw SetAudioInputNotSupportedException() |
| 142 | } |
| 143 | |
| 144 | - if (deviceInfo != null && deviceInfo.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) { |
| 145 | - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { |
| 146 | - audioManager.setCommunicationDevice(deviceInfo) |
| 147 | - } else { |
| 148 | + try { |
| 149 | + if (inputRoute != null) { |
| 150 | + inputRoute.select(deviceInfo) |
| 151 | + } else if (deviceInfo.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) { |
| 152 | audioManager.startBluetoothSco() |
| 153 | - } |
| 154 | - } else { |
| 155 | - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { |
| 156 | - audioManager.clearCommunicationDevice() |
| 157 | } else { |
| 158 | audioManager.stopBluetoothSco() |
| 159 | } |
| 160 | - } |
| 161 | - |
| 162 | - val success = recorder?.setPreferredDevice(deviceInfo) |
| 163 | - if (success == false) { |
| 164 | - throw PreferredInputNotFoundException() |
| 165 | + val source = getDeviceInfoFromUid(uid, audioManager)?.takeIf { it.isSource } |
| 166 | + if (recorder?.setPreferredDevice(source) != true) { |
| 167 | + throw PreferredInputNotFoundException() |
| 168 | + } |
| 169 | + } catch (error: Exception) { |
| 170 | + inputRoute?.close() |
| 171 | + throw error |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | private fun getDeviceInfoFromUid(uid: String, audioManager: AudioManager): AudioDeviceInfo? { |
| 176 | - val id = uid.toInt() |
| 177 | - val audioDevices: Array<AudioDeviceInfo> = audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS) |
| 178 | + val audioDevices = recordingInputs(audioManager) |
| 179 | for (device in audioDevices) { |
| 180 | - if (device.id == id) { |
| 181 | + if (recordingInputUid(device, audioDevices) == uid) { |
| 182 | return device |
| 183 | } |
| 184 | } |
| 185 | diff --git a/android/src/main/java/expo/modules/audio/AudioUtils.kt b/android/src/main/java/expo/modules/audio/AudioUtils.kt |
| 186 | index 81819c1d771bdeec093bb35a65a5e1e1af0cf9d7..b52d0cd0622c233b45115b90057c1765337e4297 100644 |
| 187 | --- a/android/src/main/java/expo/modules/audio/AudioUtils.kt |
| 188 | +++ b/android/src/main/java/expo/modules/audio/AudioUtils.kt |
| 189 | @@ -2,6 +2,8 @@ package expo.modules.audio |
| 190 | |
| 191 | import android.content.Context |
| 192 | import android.media.AudioDeviceInfo |
| 193 | +import android.media.AudioManager |
| 194 | +import android.os.Build |
| 195 | import android.os.Bundle |
| 196 | import androidx.annotation.OptIn |
| 197 | import androidx.media3.common.Player |
| 198 | @@ -17,22 +19,57 @@ fun ensureDirExists(dir: File): File { |
| 199 | return dir |
| 200 | } |
| 201 | |
| 202 | -fun getMapFromDeviceInfo(deviceInfo: AudioDeviceInfo): Bundle { |
| 203 | +fun getMapFromDeviceInfo(deviceInfo: AudioDeviceInfo, inputs: List<AudioDeviceInfo>): Bundle { |
| 204 | val map = Bundle() |
| 205 | - val type = when (deviceInfo.type) { |
| 206 | - AudioDeviceInfo.TYPE_BUILTIN_MIC -> "MicrophoneBuiltIn" |
| 207 | - AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "BluetoothSCO" |
| 208 | - AudioDeviceInfo.TYPE_BLUETOOTH_A2DP -> "BluetoothA2DP" |
| 209 | - AudioDeviceInfo.TYPE_TELEPHONY -> "Telephony" |
| 210 | - AudioDeviceInfo.TYPE_WIRED_HEADSET -> "MicrophoneWired" |
| 211 | - else -> "Unknown device type" |
| 212 | - } |
| 213 | + val type = recordingInputType(deviceInfo.type) ?: "Unknown device type" |
| 214 | map.putString("name", deviceInfo.productName.toString()) |
| 215 | map.putString("type", type) |
| 216 | - map.putString("uid", deviceInfo.id.toString()) |
| 217 | + map.putString("uid", recordingInputUid(deviceInfo, inputs)) |
| 218 | return map |
| 219 | } |
| 220 | |
| 221 | +fun recordingInputs(manager: AudioManager): List<AudioDeviceInfo> { |
| 222 | + val inputs = manager.getDevices(AudioManager.GET_DEVICES_INPUTS).filter { |
| 223 | + recordingInputType(it.type) != null |
| 224 | + } |
| 225 | + val bluetooth = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { |
| 226 | + manager.availableCommunicationDevices.filter { isBluetoothInput(it.type) } |
| 227 | + } else { |
| 228 | + emptyList() |
| 229 | + } |
| 230 | + // Some Bluetooth microphone ports appear only after the communication route is activated. |
| 231 | + return (inputs + bluetooth).distinctBy { |
| 232 | + if (isBluetoothInput(it.type)) recordingInputUid(it) else "port:${it.id}" |
| 233 | + } |
| 234 | +} |
| 235 | + |
| 236 | +internal fun isBluetoothInput(type: Int) = type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || |
| 237 | + type == AudioDeviceInfo.TYPE_BLE_HEADSET |
| 238 | + |
| 239 | +internal fun recordingInputType(type: Int): String? = when (type) { |
| 240 | + AudioDeviceInfo.TYPE_BUILTIN_MIC -> "MicrophoneBuiltIn" |
| 241 | + AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "BluetoothSCO" |
| 242 | + AudioDeviceInfo.TYPE_BLE_HEADSET -> "BluetoothLE" |
| 243 | + AudioDeviceInfo.TYPE_WIRED_HEADSET -> "MicrophoneWired" |
| 244 | + AudioDeviceInfo.TYPE_USB_DEVICE, AudioDeviceInfo.TYPE_USB_HEADSET -> "USBAudio" |
| 245 | + AudioDeviceInfo.TYPE_LINE_ANALOG, AudioDeviceInfo.TYPE_LINE_DIGITAL -> "LineIn" |
| 246 | + else -> null |
| 247 | +} |
| 248 | + |
| 249 | +fun recordingInputUid(device: AudioDeviceInfo, inputs: List<AudioDeviceInfo> = emptyList()): String { |
| 250 | + val base = recordingInputBaseUid(device) |
| 251 | + val ambiguous = !isBluetoothInput(device.type) && inputs.any { |
| 252 | + it.id != device.id && recordingInputBaseUid(it) == base |
| 253 | + } |
| 254 | + return if (ambiguous) "$base:port:${device.id}" else base |
| 255 | +} |
| 256 | + |
| 257 | +private fun recordingInputBaseUid(device: AudioDeviceInfo): String { |
| 258 | + // Port IDs and USB addresses (ALSA card numbers) change on reconnect; Bluetooth addresses don't. |
| 259 | + val stable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isBluetoothInput(device.type) |
| 260 | + return "android:${device.type}:${if (stable) device.address.ifBlank { device.productName } else device.productName}" |
| 261 | +} |
| 262 | + |
| 263 | @OptIn(UnstableApi::class) |
| 264 | fun buildBasicMediaSession(context: Context, player: Player, onPlay: () -> Unit): MediaSession { |
| 265 | return MediaSession.Builder(context, PlayRequestingPlayer(player, onPlay)) |
| 266 | diff --git a/android/src/main/java/expo/modules/audio/RecordingInputRoute.kt b/android/src/main/java/expo/modules/audio/RecordingInputRoute.kt |
| 267 | new file mode 100644 |
| 268 | index 0000000000000000000000000000000000000000..372ab7554df73f043b9cb832a6b1d769d2ed69bf |
| 269 | --- /dev/null |
| 270 | +++ b/android/src/main/java/expo/modules/audio/RecordingInputRoute.kt |
| 271 | @@ -0,0 +1,53 @@ |
| 272 | +package expo.modules.audio |
| 273 | + |
| 274 | +import android.media.AudioDeviceInfo |
| 275 | +import android.media.AudioManager |
| 276 | +import androidx.annotation.RequiresApi |
| 277 | +import java.io.Closeable |
| 278 | +import java.util.concurrent.Executor |
| 279 | +import kotlinx.coroutines.CompletableDeferred |
| 280 | +import kotlinx.coroutines.withTimeout |
| 281 | + |
| 282 | +@RequiresApi(31) |
| 283 | +class RecordingInputRoute(private val manager: AudioManager) : Closeable { |
| 284 | + private var previousMode: Int? = null |
| 285 | + |
| 286 | + suspend fun select(input: AudioDeviceInfo) { |
| 287 | + if (!isBluetoothInput(input.type)) { |
| 288 | + close() |
| 289 | + return |
| 290 | + } |
| 291 | + // Communication routing takes the headset's output; Android pairs its microphone. |
| 292 | + val output = manager.availableCommunicationDevices.firstOrNull { |
| 293 | + it.isSink && it.type == input.type && |
| 294 | + if (input.address.isNotBlank()) it.address == input.address else it.productName == input.productName |
| 295 | + } ?: throw PreferredInputNotFoundException() |
| 296 | + val ready = CompletableDeferred<Unit>() |
| 297 | + val listener = AudioManager.OnCommunicationDeviceChangedListener { |
| 298 | + if (it?.id == output.id) ready.complete(Unit) |
| 299 | + } |
| 300 | + manager.addOnCommunicationDeviceChangedListener(Executor { it.run() }, listener) |
| 301 | + try { |
| 302 | + if (previousMode == null) previousMode = manager.mode |
| 303 | + manager.mode = AudioManager.MODE_IN_COMMUNICATION |
| 304 | + if (!manager.setCommunicationDevice(output)) throw PreferredInputNotFoundException() |
| 305 | + if (manager.communicationDevice?.id == output.id) ready.complete(Unit) |
| 306 | + withTimeout(5_000) { ready.await() } |
| 307 | + } catch (error: Exception) { |
| 308 | + close() |
| 309 | + throw error |
| 310 | + } finally { |
| 311 | + manager.removeOnCommunicationDeviceChangedListener(listener) |
| 312 | + } |
| 313 | + } |
| 314 | + |
| 315 | + override fun close() { |
| 316 | + val mode = previousMode ?: return |
| 317 | + previousMode = null |
| 318 | + try { |
| 319 | + manager.clearCommunicationDevice() |
| 320 | + } finally { |
| 321 | + if (manager.mode == AudioManager.MODE_IN_COMMUNICATION) manager.mode = mode |
| 322 | + } |
| 323 | + } |
| 324 | +} |
| 325 | diff --git a/android/src/test/java/expo/modules/audio/RecordingInputIdentityTest.kt b/android/src/test/java/expo/modules/audio/RecordingInputIdentityTest.kt |
| 326 | new file mode 100644 |
| 327 | index 0000000000000000000000000000000000000000..4dd0567e2170770e9b0f6a17dc4581bc769d5c6a |
| 328 | --- /dev/null |
| 329 | +++ b/android/src/test/java/expo/modules/audio/RecordingInputIdentityTest.kt |
| 330 | @@ -0,0 +1,35 @@ |
| 331 | +package expo.modules.audio |
| 332 | + |
| 333 | +import android.media.AudioDeviceInfo |
| 334 | +import android.media.AudioManager |
| 335 | +import io.mockk.every |
| 336 | +import io.mockk.mockk |
| 337 | +import org.junit.Assert.* |
| 338 | +import org.junit.Test |
| 339 | + |
| 340 | +class RecordingInputIdentityTest { |
| 341 | + private fun device(id: Int) = mockk<AudioDeviceInfo> { |
| 342 | + every { this@mockk.id } returns id |
| 343 | + every { type } returns AudioDeviceInfo.TYPE_USB_DEVICE |
| 344 | + every { productName } returns "USB Microphone" |
| 345 | + every { address } returns "card=$id;device=0;" |
| 346 | + } |
| 347 | + |
| 348 | + @Test |
| 349 | + fun identicalUsbMicrophonesRemainSelectable() { |
| 350 | + val first = device(1) |
| 351 | + val second = device(2) |
| 352 | + val manager = mockk<AudioManager> { |
| 353 | + every { getDevices(AudioManager.GET_DEVICES_INPUTS) } returns arrayOf(first, second) |
| 354 | + } |
| 355 | + val inputs = recordingInputs(manager) |
| 356 | + assertEquals(2, inputs.size) |
| 357 | + val firstUid = recordingInputUid(first, inputs) |
| 358 | + val secondUid = recordingInputUid(second, inputs) |
| 359 | + assertNotEquals(firstUid, secondUid) |
| 360 | + assertSame(first, inputs.single { recordingInputUid(it, inputs) == firstUid }) |
| 361 | + assertSame(second, inputs.single { recordingInputUid(it, inputs) == secondUid }) |
| 362 | + val reconnected = device(99) |
| 363 | + assertEquals(recordingInputUid(first, listOf(first)), recordingInputUid(reconnected, listOf(reconnected))) |
| 364 | + } |
| 365 | +} |
| 366 | diff --git a/build/AudioModule.types.d.ts b/build/AudioModule.types.d.ts |
| 367 | index 0d63c9b949cfae7a101902fc3bb70fcf46094f68..a312b8fcdaf728220db3d6c04d92fd78a4aa101c 100644 |
| 368 | --- a/build/AudioModule.types.d.ts |
| 369 | +++ b/build/AudioModule.types.d.ts |
| 370 | @@ -8,6 +8,8 @@ import type { AudioStream } from './AudioStream.types'; |
| 371 | */ |
| 372 | export declare class NativeAudioModule extends NativeModule { |
| 373 | setIsAudioActiveAsync(active: boolean): Promise<void>; |
| 374 | + /** iOS only: protect the shared session from delayed expo-audio deactivation. */ |
| 375 | + setAudioSessionOwner?(owned: boolean): void; |
| 376 | setAudioModeAsync(category: Partial<AudioMode>): Promise<void>; |
| 377 | requestRecordingPermissionsAsync(): Promise<PermissionResponse>; |
| 378 | requestNotificationPermissionsAsync(): Promise<PermissionResponse>; |
| 379 | @@ -135,8 +137,9 @@ export declare class AudioPlayer extends SharedObject<AudioEvents> { |
| 380 | play(): void; |
| 381 | /** |
| 382 | * Pauses the player. |
| 383 | + * @param deactivateSession On iOS, pass false when handing the shared session to another player. |
| 384 | */ |
| 385 | - pause(): void; |
| 386 | + pause(deactivateSession?: boolean): void; |
| 387 | /** |
| 388 | * Replaces the current audio source with a new one. |
| 389 | */ |
| 390 | diff --git a/ios/AudioModule.swift b/ios/AudioModule.swift |
| 391 | --- a/ios/AudioModule.swift |
| 392 | +++ b/ios/AudioModule.swift |
| 393 | @@ -6,6 +6,7 @@ public class AudioModule: Module { |
| 394 | |
| 395 | private let sessionQueue = DispatchQueue(label: "expo.modules.audio.session", qos: .userInitiated) |
| 396 | private var sessionIsActive = false |
| 397 | + private var hasAudioSessionOwner = false |
| 398 | private var audioSessionActivityKeepers = Set<String>() |
| 399 | private let audioEnabled = OSAllocatedUnfairLock(initialState: true) |
| 400 | |
| 401 | @@ -41,6 +42,16 @@ public class AudioModule: Module { |
| 402 | try setIsAudioActive(isActive) |
| 403 | } |
| 404 | |
| 405 | + // Video shares AVAudioSession but is absent from this module's registry. |
| 406 | + Function("setAudioSessionOwner") { (owned: Bool) in |
| 407 | + self.sessionQueue.sync { |
| 408 | + self.hasAudioSessionOwner = owned |
| 409 | + if !owned { |
| 410 | + self.deactivateSession() |
| 411 | + } |
| 412 | + } |
| 413 | + } |
| 414 | + |
| 415 | AsyncFunction("requestRecordingPermissionsAsync") { (promise: Promise) in |
| 416 | #if os(iOS) |
| 417 | appContext?.permissions?.askForPermission( |
| 418 | @@ -259,9 +270,9 @@ public class AudioModule: Module { |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | - Function("pause") { player in |
| 423 | + Function("pause") { (player: AudioPlayer, deactivateSession: Bool?) in |
| 424 | player.ref.pause() |
| 425 | - if !player.keepAudioSessionActive { |
| 426 | + if deactivateSession != false && !player.keepAudioSessionActive { |
| 427 | self.deactivateSession() |
| 428 | } |
| 429 | } |
| 430 | @@ -486,11 +497,12 @@ public class AudioModule: Module { |
| 431 | AsyncFunction("prepareToRecordAsync") { (recorder, options: RecordingOptions?) in |
| 432 | try AudioRecordingRequester.requireUsageDescription() |
| 433 | - let deactivateSessionOnFailure = sessionQueue.sync { |
| 434 | - !sessionIsActive && audioSessionActivityKeepers.isEmpty |
| 435 | + let (activateSession, deactivateSessionOnFailure) = sessionQueue.sync { |
| 436 | + (!hasAudioSessionOwner || !sessionIsActive, !sessionIsActive && audioSessionActivityKeepers.isEmpty) |
| 437 | } |
| 438 | try recorder.prepare( |
| 439 | options: options, |
| 440 | sessionOptions: sessionOptions, |
| 441 | + activateSession: activateSession, |
| 442 | deactivateSessionOnFailure: deactivateSessionOnFailure |
| 443 | ) |
| 444 | recordSessionActive(true) |
| 445 | @@ -957,6 +969,7 @@ public class AudioModule: Module { |
| 446 | sessionQueue.asyncAfter(deadline: .now() + .milliseconds(100)) { [weak self] in |
| 447 | guard let self, |
| 448 | self.sessionIsActive, |
| 449 | + !self.hasAudioSessionOwner, |
| 450 | self.audioSessionActivityKeepers.isEmpty, |
| 451 | !self.isSessionInUse else { |
| 452 | return |
| 453 | diff --git a/ios/AudioRecorder.swift b/ios/AudioRecorder.swift |
| 454 | --- a/ios/AudioRecorder.swift |
| 455 | +++ b/ios/AudioRecorder.swift |
| 456 | @@ -81,6 +81,7 @@ class AudioRecorder: SharedRef<AVAudioRecorder>, RecordingResultHandler { |
| 457 | func prepare( |
| 458 | options: RecordingOptions?, |
| 459 | sessionOptions: AVAudioSession.CategoryOptions = [], |
| 460 | + activateSession: Bool = true, |
| 461 | deactivateSessionOnFailure: Bool = true |
| 462 | ) throws { |
| 463 | if currentState == .recording { |
| 464 | @@ -93,7 +94,12 @@ class AudioRecorder: SharedRef<AVAudioRecorder>, RecordingResultHandler { |
| 465 | let session = AVAudioSession.sharedInstance() |
| 466 | do { |
| 467 | - try session.setCategory(.playAndRecord, mode: .default, options: sessionOptions) |
| 468 | - try session.setActive(true) |
| 469 | + let categoryMatches = session.category == .playAndRecord && session.mode == .default && session.categoryOptions == sessionOptions |
| 470 | + if !categoryMatches { |
| 471 | + try session.setCategory(.playAndRecord, mode: .default, options: sessionOptions) |
| 472 | + } |
| 473 | + if activateSession || !categoryMatches { |
| 474 | + try session.setActive(true) |
| 475 | + } |
| 476 | } catch { |
| 477 | currentState = .error |
| 478 | throw AudioRecordingException("Failed to configure audio session: \(error.localizedDescription)") |
| 479 | @@ -285,16 +291,16 @@ class AudioRecorder: SharedRef<AVAudioRecorder>, RecordingResultHandler { |
| 480 | } |
| 481 | |
| 482 | func didFinish(_ recorder: AVAudioRecorder, successfully flag: Bool) { |
| 483 | - // Update internal state when recording finishes automatically (e.g., from recordForDuration) |
| 484 | - currentState = .stopped |
| 485 | + // Update internal state when AVAudioRecorder finishes or fails. |
| 486 | + currentState = flag ? .stopped : .error |
| 487 | resetDurationTracking() |
| 488 | durationLimitSeconds = nil |
| 489 | |
| 490 | emit(event: recordingStatus, payload: [ |
| 491 | "id": id, |
| 492 | "isFinished": true, |
| 493 | - "hasError": false, |
| 494 | - "error": nil, |
| 495 | + "hasError": !flag, |
| 496 | + "error": flag ? nil : "Recording failed", |
| 497 | "url": recorder.url.absoluteString |
| 498 | ]) |
| 499 | } |
| 500 | diff --git a/ios/AudioUtils.swift b/ios/AudioUtils.swift |
| 501 | --- a/ios/AudioUtils.swift |
| 502 | +++ b/ios/AudioUtils.swift |
| 503 | @@ -23,4 +23,9 @@ struct RecordingUtils { |
| 504 | static func setInput(_ input: String) throws { |
| 505 | + let session = AVAudioSession.sharedInstance() |
| 506 | + if session.currentRoute.inputs.first?.uid == input && session.preferredInput?.uid == input { |
| 507 | + return |
| 508 | + } |
| 509 | + |
| 510 | var preferredInput: AVAudioSessionPortDescription? |
| 511 | if let currentInputs = AVAudioSession.sharedInstance().availableInputs { |
| 512 | for desc in currentInputs where desc.uid == input { |
| 513 | diff --git a/src/AudioModule.types.ts b/src/AudioModule.types.ts |
| 514 | index 3194a8ebd1b91793d03a1692c563b5d2e83c2738..d8822a6c2ad8a581275e2ca428f4b5d0ed961be2 100644 |
| 515 | --- a/src/AudioModule.types.ts |
| 516 | +++ b/src/AudioModule.types.ts |
| 517 | @@ -24,6 +24,8 @@ import type { AudioStream } from './AudioStream.types'; |
| 518 | */ |
| 519 | export declare class NativeAudioModule extends NativeModule { |
| 520 | setIsAudioActiveAsync(active: boolean): Promise<void>; |
| 521 | + /** iOS only: protect the shared session from delayed expo-audio deactivation. */ |
| 522 | + setAudioSessionOwner?(owned: boolean): void; |
| 523 | setAudioModeAsync(category: Partial<AudioMode>): Promise<void>; |
| 524 | requestRecordingPermissionsAsync(): Promise<PermissionResponse>; |
| 525 | requestNotificationPermissionsAsync(): Promise<PermissionResponse>; |
| 526 | @@ -175,8 +177,9 @@ export declare class AudioPlayer extends SharedObject<AudioEvents> { |
| 527 | |
| 528 | /** |
| 529 | * Pauses the player. |
| 530 | + * @param deactivateSession On iOS, pass false when handing the shared session to another player. |
| 531 | */ |
| 532 | - pause(): void; |
| 533 | + pause(deactivateSession?: boolean): void; |
| 534 | |
| 535 | /** |
| 536 | * Replaces the current audio source with a new one. |