diff --git a/ios/AudioRecorder.swift b/ios/AudioRecorder.swift
index 198fe6d..5b39611 100644
--- a/ios/AudioRecorder.swift
+++ b/ios/AudioRecorder.swift
@@ -285,16 +285,16 @@ class AudioRecorder: SharedRef<AVAudioRecorder>, RecordingResultHandler {
}
func didFinish(_ recorder: AVAudioRecorder, successfully flag: Bool) {
- // Update internal state when recording finishes automatically (e.g., from recordForDuration)
- currentState = .stopped
+ // Update internal state when AVAudioRecorder finishes or fails.
+ currentState = flag ? .stopped : .error
resetDurationTracking()
durationLimitSeconds = nil
emit(event: recordingStatus, payload: [
"id": id,
"isFinished": true,
- "hasError": false,
- "error": nil,
+ "hasError": !flag,
+ "error": flag ? nil : "Recording failed",
"url": recorder.url.absoluteString
])
}
diff --git a/ios/AudioModule.swift b/ios/AudioModule.swift
--- a/ios/AudioModule.swift
+++ b/ios/AudioModule.swift
@@ -6,6 +6,7 @@
private let sessionQueue = DispatchQueue(label: "expo.modules.audio.session", qos: .userInitiated)
private var sessionIsActive = false
+ private var hasAudioSessionOwner = false
private var audioSessionActivityKeepers = Set<String>()
private let audioEnabled = OSAllocatedUnfairLock(initialState: true)
@@ -41,6 +42,16 @@
try setIsAudioActive(isActive)
}
+ // Video shares AVAudioSession but is absent from this module's registry.
+ Function("setAudioSessionOwner") { (owned: Bool) in
+ self.sessionQueue.sync {
+ self.hasAudioSessionOwner = owned
+ if !owned {
+ self.deactivateSession()
+ }
+ }
+ }
+
AsyncFunction("requestRecordingPermissionsAsync") { (promise: Promise) in
#if os(iOS)
appContext?.permissions?.askForPermission(
@@ -259,9 +259,9 @@
}
}
- Function("pause") { player in
+ Function("pause") { (player: AudioPlayer, deactivateSession: Bool?) in
player.ref.pause()
- if !player.keepAudioSessionActive {
+ if deactivateSession != false && !player.keepAudioSessionActive {
self.deactivateSession()
}
}
@@ -957,6 +967,7 @@
sessionQueue.asyncAfter(deadline: .now() + .milliseconds(100)) { [weak self] in
guard let self,
self.sessionIsActive,
+ !self.hasAudioSessionOwner,
self.audioSessionActivityKeepers.isEmpty,
!self.isSessionInUse else {
return
diff --git a/src/AudioModule.types.ts b/src/AudioModule.types.ts
index 3194a8ebd1b91793d03a1692c563b5d2e83c2738..e7e713199f776b60093b75da782197427cf2000d 100644
--- a/src/AudioModule.types.ts
+++ b/src/AudioModule.types.ts
@@ -24,6 +24,8 @@ import type { AudioStream } from './AudioStream.types';
*/
export declare class NativeAudioModule extends NativeModule {
setIsAudioActiveAsync(active: boolean): Promise<void>;
+ /** iOS only: protect the shared session from delayed expo-audio deactivation. */
+ setAudioSessionOwner?(owned: boolean): void;
setAudioModeAsync(category: Partial<AudioMode>): Promise<void>;
requestRecordingPermissionsAsync(): Promise<PermissionResponse>;
requestNotificationPermissionsAsync(): Promise<PermissionResponse>;
@@ -175,8 +177,9 @@ export declare class AudioPlayer extends SharedObject<AudioEvents> {
/**
* Pauses the player.
+ * @param deactivateSession On iOS, pass false when handing the shared session to another player.
*/
- pause(): void;
+ pause(deactivateSession?: boolean): void;
/**
* Replaces the current audio source with a new one.
diff --git a/build/AudioModule.types.d.ts b/build/AudioModule.types.d.ts
index 0d63c9b949cfae7a101902fc3bb70fcf46094f68..b590f9654bbf74b5052b71e31b7ed6d3d0050aa4 100644
--- a/build/AudioModule.types.d.ts
+++ b/build/AudioModule.types.d.ts
@@ -8,6 +8,8 @@ import type { AudioStream } from './AudioStream.types';
*/
export declare class NativeAudioModule extends NativeModule {
setIsAudioActiveAsync(active: boolean): Promise<void>;
+ /** iOS only: protect the shared session from delayed expo-audio deactivation. */
+ setAudioSessionOwner?(owned: boolean): void;
setAudioModeAsync(category: Partial<AudioMode>): Promise<void>;
requestRecordingPermissionsAsync(): Promise<PermissionResponse>;
requestNotificationPermissionsAsync(): Promise<PermissionResponse>;
@@ -135,8 +137,9 @@ export declare class AudioPlayer extends SharedObject<AudioEvents> {
play(): void;
/**
* Pauses the player.
+ * @param deactivateSession On iOS, pass false when handing the shared session to another player.
*/
- pause(): void;
+ pause(deactivateSession?: boolean): void;
/**
* Replaces the current audio source with a new one.
*/
diff --git a/android/src/main/java/expo/modules/audio/AudioModule.kt b/android/src/main/java/expo/modules/audio/AudioModule.kt
index 6c81fce3dd518d3b82e3280940a001c7be84dd0a..16125c679c870e2eae48f8db953dedd3fc842c3d 100644
--- a/android/src/main/java/expo/modules/audio/AudioModule.kt
+++ b/android/src/main/java/expo/modules/audio/AudioModule.kt
@@ -677,7 +677,7 @@ class AudioModule : Module() {
}
}
- Function("pause") { player: AudioPlayer ->
+ Function("pause") { player: AudioPlayer, /* deactivateSession - iOS only */ _: Boolean? ->
runOnMain {
player.isPaused = false
player.ref.pause()
@@ -824,10 +824,14 @@ class AudioModule : Module() {
return@Function recorder.getAvailableInputs(audioManager)
}
- Function("setInput") { recorder: AudioRecorder, input: String ->
+ AsyncFunction("setInput") Coroutine { recorder: AudioRecorder, input: String ->
recorder.setInput(input, audioManager)
}
+ Function("cancelInputSelection") { recorder: AudioRecorder ->
+ recorder.cancelInputSelection()
+ }
+
Function("startRecordingAtTime") { recorder: AudioRecorder, seconds: Double ->
checkRecordingPermission()
if (recorder.isPrepared) {
diff --git a/android/src/main/java/expo/modules/audio/AudioRecorder.kt b/android/src/main/java/expo/modules/audio/AudioRecorder.kt
index 2ff4a474fdea3efa652436a8a3960c3669ad298b..1ced279991294d3d81cb20fa339ca73e5d6d6c01 100644
--- a/android/src/main/java/expo/modules/audio/AudioRecorder.kt
+++ b/android/src/main/java/expo/modules/audio/AudioRecorder.kt
@@ -19,6 +19,9 @@ import expo.modules.kotlin.exception.CodedException
import expo.modules.kotlin.exception.Exceptions
import expo.modules.kotlin.sharedobjects.SharedObject
import kotlinx.coroutines.Job
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
@@ -42,12 +45,19 @@ class AudioRecorder(
var isPrepared = false
private var recorder: MediaRecorder? = null
+ private val inputRoute = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ RecordingInputRoute(context.getSystemService(Context.AUDIO_SERVICE) as AudioManager)
+ } else {
+ null
+ }
val id = UUID.randomUUID().toString()
var startTime = 0L
var isRecording = false
var isPaused = false
private var isPausedBySystem = false
private var recordingTimerJob: Job? = null
+ private var inputSelectionJob: Job? = null
+ private var inputSelectionCanceled = false
private var durationLimitMillis: Long? = null
var useForegroundService = false
@@ -90,6 +100,7 @@ class AudioRecorder(
throw AudioRecorderAlreadyPreparedException()
}
+ synchronized(this) { inputSelectionCanceled = false }
val recordingOptions = options ?: this.options
val mediaRecorder = createRecorder(recordingOptions)
recorder = mediaRecorder
@@ -245,10 +256,15 @@ class AudioRecorder(
}
private fun reset() {
+ cancelInputSelection()
recordingTimerJob?.cancel()
recordingTimerJob = null
- recorder?.release()
+ try {
+ recorder?.release()
+ } finally {
+ inputRoute?.close()
+ }
recorder = null
isRecording = false
isPaused = false
@@ -468,55 +484,68 @@ class AudioRecorder(
throw DeviceInfoNotFoundException()
}
- return getMapFromDeviceInfo(deviceInfo)
+ return getMapFromDeviceInfo(deviceInfo, recordingInputs(audioManager))
}
private fun hasRecordingPermissions() =
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
- fun getAvailableInputs(audioManager: AudioManager) =
- audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS).mapNotNull { deviceInfo ->
- val type = deviceInfo.type
- if (type == AudioDeviceInfo.TYPE_BUILTIN_MIC || type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || type == AudioDeviceInfo.TYPE_WIRED_HEADSET) {
- getMapFromDeviceInfo(deviceInfo)
- } else {
- null
- }
+ fun getAvailableInputs(audioManager: AudioManager): List<Bundle> {
+ val inputs = recordingInputs(audioManager)
+ return inputs.map { getMapFromDeviceInfo(it, inputs) }
+ }
+
+ suspend fun setInput(uid: String, audioManager: AudioManager) {
+ val job = currentCoroutineContext().job
+ synchronized(this) {
+ if (inputSelectionCanceled) throw CancellationException("Input selection canceled")
+ inputSelectionJob = job
+ }
+ try {
+ setInputDevice(uid, audioManager)
+ } finally {
+ synchronized(this) { if (inputSelectionJob === job) inputSelectionJob = null }
}
+ }
+
+ fun cancelInputSelection() {
+ val job = synchronized(this) {
+ inputSelectionCanceled = true
+ inputSelectionJob
+ }
+ job?.cancel()
+ }
@Suppress("DEPRECATION")
- fun setInput(uid: String, audioManager: AudioManager) {
- val deviceInfo: AudioDeviceInfo? = getDeviceInfoFromUid(uid, audioManager)
+ private suspend fun setInputDevice(uid: String, audioManager: AudioManager) {
+ val deviceInfo = getDeviceInfoFromUid(uid, audioManager) ?: throw PreferredInputNotFoundException()
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
throw SetAudioInputNotSupportedException()
}
- if (deviceInfo != null && deviceInfo.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- audioManager.setCommunicationDevice(deviceInfo)
- } else {
+ try {
+ if (inputRoute != null) {
+ inputRoute.select(deviceInfo)
+ } else if (deviceInfo.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
audioManager.startBluetoothSco()
- }
- } else {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- audioManager.clearCommunicationDevice()
} else {
audioManager.stopBluetoothSco()
}
- }
-
- val success = recorder?.setPreferredDevice(deviceInfo)
- if (success == false) {
- throw PreferredInputNotFoundException()
+ val source = getDeviceInfoFromUid(uid, audioManager)?.takeIf { it.isSource }
+ if (recorder?.setPreferredDevice(source) != true) {
+ throw PreferredInputNotFoundException()
+ }
+ } catch (error: Exception) {
+ inputRoute?.close()
+ throw error
}
}
private fun getDeviceInfoFromUid(uid: String, audioManager: AudioManager): AudioDeviceInfo? {
- val id = uid.toInt()
- val audioDevices: Array<AudioDeviceInfo> = audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)
+ val audioDevices = recordingInputs(audioManager)
for (device in audioDevices) {
- if (device.id == id) {
+ if (recordingInputUid(device, audioDevices) == uid) {
return device
}
}
diff --git a/android/src/main/java/expo/modules/audio/AudioUtils.kt b/android/src/main/java/expo/modules/audio/AudioUtils.kt
index 81819c1d771bdeec093bb35a65a5e1e1af0cf9d7..cd0c7624b4cd8a4ebf7ed3b3390cfc76802e8530 100644
--- a/android/src/main/java/expo/modules/audio/AudioUtils.kt
+++ b/android/src/main/java/expo/modules/audio/AudioUtils.kt
@@ -2,6 +2,8 @@ package expo.modules.audio
import android.content.Context
import android.media.AudioDeviceInfo
+import android.media.AudioManager
+import android.os.Build
import android.os.Bundle
import androidx.annotation.OptIn
import androidx.media3.common.Player
@@ -17,22 +19,57 @@ fun ensureDirExists(dir: File): File {
return dir
}
-fun getMapFromDeviceInfo(deviceInfo: AudioDeviceInfo): Bundle {
+fun getMapFromDeviceInfo(deviceInfo: AudioDeviceInfo, inputs: List<AudioDeviceInfo>): Bundle {
val map = Bundle()
- val type = when (deviceInfo.type) {
- AudioDeviceInfo.TYPE_BUILTIN_MIC -> "MicrophoneBuiltIn"
- AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "BluetoothSCO"
- AudioDeviceInfo.TYPE_BLUETOOTH_A2DP -> "BluetoothA2DP"
- AudioDeviceInfo.TYPE_TELEPHONY -> "Telephony"
- AudioDeviceInfo.TYPE_WIRED_HEADSET -> "MicrophoneWired"
- else -> "Unknown device type"
- }
+ val type = recordingInputType(deviceInfo.type) ?: "Unknown device type"
map.putString("name", deviceInfo.productName.toString())
map.putString("type", type)
- map.putString("uid", deviceInfo.id.toString())
+ map.putString("uid", recordingInputUid(deviceInfo, inputs))
return map
}
+fun recordingInputs(manager: AudioManager): List<AudioDeviceInfo> {
+ val inputs = manager.getDevices(AudioManager.GET_DEVICES_INPUTS).filter {
+ recordingInputType(it.type) != null
+ }
+ val bluetooth = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ manager.availableCommunicationDevices.filter { isBluetoothInput(it.type) }
+ } else {
+ emptyList()
+ }
+ // Some Bluetooth microphone ports appear only after the communication route is activated.
+ return (inputs + bluetooth).distinctBy {
+ if (isBluetoothInput(it.type)) recordingInputUid(it) else "port:${it.id}"
+ }
+}
+
+internal fun isBluetoothInput(type: Int) = type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO ||
+ type == AudioDeviceInfo.TYPE_BLE_HEADSET
+
+internal fun recordingInputType(type: Int): String? = when (type) {
+ AudioDeviceInfo.TYPE_BUILTIN_MIC -> "MicrophoneBuiltIn"
+ AudioDeviceInfo.TYPE_BLUETOOTH_SCO -> "BluetoothSCO"
+ AudioDeviceInfo.TYPE_BLE_HEADSET -> "BluetoothLE"
+ AudioDeviceInfo.TYPE_WIRED_HEADSET -> "MicrophoneWired"
+ AudioDeviceInfo.TYPE_USB_DEVICE, AudioDeviceInfo.TYPE_USB_HEADSET -> "USBAudio"
+ AudioDeviceInfo.TYPE_LINE_ANALOG, AudioDeviceInfo.TYPE_LINE_DIGITAL -> "LineIn"
+ else -> null
+}
+
+fun recordingInputUid(device: AudioDeviceInfo, inputs: List<AudioDeviceInfo> = emptyList()): String {
+ val base = recordingInputBaseUid(device)
+ val ambiguous = !isBluetoothInput(device.type) && inputs.any {
+ it.id != device.id && recordingInputBaseUid(it) == base
+ }
+ return if (ambiguous) "$base:port:${device.id}" else base
+}
+
+private fun recordingInputBaseUid(device: AudioDeviceInfo): String {
+ // Port IDs and USB addresses (ALSA card numbers) change on reconnect; Bluetooth addresses don't.
+ val stable = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isBluetoothInput(device.type)
+ return "android:${device.type}:${if (stable) device.address.ifBlank { device.productName } else device.productName}"
+}
+
@OptIn(UnstableApi::class)
fun buildBasicMediaSession(context: Context, player: Player, onPlay: () -> Unit): MediaSession {
return MediaSession.Builder(context, PlayRequestingPlayer(player, onPlay))
diff --git a/android/src/main/java/expo/modules/audio/RecordingInputRoute.kt b/android/src/main/java/expo/modules/audio/RecordingInputRoute.kt
new file mode 100644
index 0000000000000000000000000000000000000000..cdba9724318cf06afd21b4df6b895b381afa8e6f
--- /dev/null
+++ b/android/src/main/java/expo/modules/audio/RecordingInputRoute.kt
@@ -0,0 +1,53 @@
+package expo.modules.audio
+
+import android.media.AudioDeviceInfo
+import android.media.AudioManager
+import androidx.annotation.RequiresApi
+import java.io.Closeable
+import java.util.concurrent.Executor
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.withTimeout
+
+@RequiresApi(31)
+class RecordingInputRoute(private val manager: AudioManager) : Closeable {
+ private var previousMode: Int? = null
+
+ suspend fun select(input: AudioDeviceInfo) {
+ if (!isBluetoothInput(input.type)) {
+ close()
+ return
+ }
+ // Communication routing takes the headset's output; Android pairs its microphone.
+ val output = manager.availableCommunicationDevices.firstOrNull {
+ it.isSink && it.type == input.type &&
+ if (input.address.isNotBlank()) it.address == input.address else it.productName == input.productName
+ } ?: throw PreferredInputNotFoundException()
+ val ready = CompletableDeferred<Unit>()
+ val listener = AudioManager.OnCommunicationDeviceChangedListener {
+ if (it?.id == output.id) ready.complete(Unit)
+ }
+ manager.addOnCommunicationDeviceChangedListener(Executor { it.run() }, listener)
+ try {
+ if (previousMode == null) previousMode = manager.mode
+ manager.mode = AudioManager.MODE_IN_COMMUNICATION
+ if (!manager.setCommunicationDevice(output)) throw PreferredInputNotFoundException()
+ if (manager.communicationDevice?.id == output.id) ready.complete(Unit)
+ withTimeout(5_000) { ready.await() }
+ } catch (error: Exception) {
+ close()
+ throw error
+ } finally {
+ manager.removeOnCommunicationDeviceChangedListener(listener)
+ }
+ }
+
+ override fun close() {
+ val mode = previousMode ?: return
+ previousMode = null
+ try {
+ manager.clearCommunicationDevice()
+ } finally {
+ if (manager.mode == AudioManager.MODE_IN_COMMUNICATION) manager.mode = mode
+ }
+ }
+}
diff --git a/android/src/test/java/expo/modules/audio/RecordingInputIdentityTest.kt b/android/src/test/java/expo/modules/audio/RecordingInputIdentityTest.kt
new file mode 100644
index 0000000000000000000000000000000000000000..4dd0567e2170770e9b0f6a17dc4581bc769d5c6a
--- /dev/null
+++ b/android/src/test/java/expo/modules/audio/RecordingInputIdentityTest.kt
@@ -0,0 +1,35 @@
+package expo.modules.audio
+
+import android.media.AudioDeviceInfo
+import android.media.AudioManager
+import io.mockk.every
+import io.mockk.mockk
+import org.junit.Assert.*
+import org.junit.Test
+
+class RecordingInputIdentityTest {
+ private fun device(id: Int) = mockk<AudioDeviceInfo> {
+ every { this@mockk.id } returns id
+ every { type } returns AudioDeviceInfo.TYPE_USB_DEVICE
+ every { productName } returns "USB Microphone"
+ every { address } returns "card=$id;device=0;"
+ }
+
+ @Test
+ fun identicalUsbMicrophonesRemainSelectable() {
+ val first = device(1)
+ val second = device(2)
+ val manager = mockk<AudioManager> {
+ every { getDevices(AudioManager.GET_DEVICES_INPUTS) } returns arrayOf(first, second)
+ }
+ val inputs = recordingInputs(manager)
+ assertEquals(2, inputs.size)
+ val firstUid = recordingInputUid(first, inputs)
+ val secondUid = recordingInputUid(second, inputs)
+ assertNotEquals(firstUid, secondUid)
+ assertSame(first, inputs.single { recordingInputUid(it, inputs) == firstUid })
+ assertSame(second, inputs.single { recordingInputUid(it, inputs) == secondUid })
+ val reconnected = device(99)
+ assertEquals(recordingInputUid(first, listOf(first)), recordingInputUid(reconnected, listOf(reconnected)))
+ }
+}