AudioManager
The AudioManager is a layer of an abstraction between user and a system.
It provides a set of system-specific functions that are invoked directly in native code, by related system.
Example
import { AudioManager } from 'react-native-audio-api';
import { useEffect } from 'react';
function App() {
// set AVAudioSession example options (iOS)
AudioManager.setSystemOptions({
ios: {
category: 'playback',
mode: 'default',
options: ['allowBluetoothHFP', 'allowAirPlay'],
},
})
// enabling emission of events
AudioManager.observeAudioInterruptions(true);
AudioManager.getDevicesInfo().then(console.log);
useEffect(() => {
// callback to be invoked on 'interruption' event
const interruptionSubscription = AudioManager.addSystemEventListener(
'interruption',
(event) => {
console.log('Interruption event:', event);
}
);
return () => {
interruptionSubscription?.remove();
};
}, []);
}
Methods
setSystemOptions Mobile only
| Parameter | Type | Description |
|---|---|---|
| options | SystemOptions | Platform options, grouped under ios (AVAudioSession settings) and android (audio mode and communication route). Each group is ignored on the other platform. |
Returns undefined.
On Android 12 (API 31) or later, set android: { mode: 'inCommunication' } before activating the session to request Android's communication audio mode. The optional android.communicationDevice requests 'speaker', 'earpiece', or 'systemDefault' as the initial route. Existing Android behavior is unchanged when android.mode is omitted.
setAudioSessionActivity Mobile only
| Parameter | Type | Description |
|---|---|---|
| enabled | boolean | Activates or deactivates the platform audio session. On iOS this sets AVAudioSession activity. On Android it has an effect only with android: { mode: 'inCommunication' } from setSystemOptions(), where it acquires or releases the communication session described below. |
Returns Promise<void>, which resolves when the audio session activity was set successfully. On failure, the promise rejects with a SessionActivationError that carries the native error details (nativeErrorInfo) when available.
Deactivating the session while a recording is in progress or paused stops that recording first, since an inactive session would corrupt its output. The finalized files are then available through AudioRecorder.consumeLastRecordingResult(). Prefer calling AudioRecorder.stop() yourself before deactivating, so the file info arrives through its promise.
With Android inCommunication mode, activation requests transient focus using voice-communication/speech attributes, enters MODE_IN_COMMUNICATION, and applies the configured initial communication-device preference. Deactivation clears the request, abandons that focus, and restores the prior mode. Activation rejects below API 31 or if Android denies focus or the requested route. After a permanent focus loss, deactivate the session before starting a new one; the library does not reacquire focus automatically.
setCommunicationDevice Android 12+ (API 31)
Requests the Android route for voice-communication audio. It works with or without an inCommunication session and only affects streams with the voiceCommunication output profile. Without a session Android sends those streams to the earpiece by default, so request 'speaker' for a loudspeaker route.
| Parameter | Type | Description |
|---|---|---|
device | CommunicationDevice | The route to request. |
Returns Promise<void>, which rejects if the requested built-in device is unavailable or Android rejects the request.
Android keeps the request until you request 'systemDefault', call setAudioSessionActivity(false), or the app process ends. The next activation applies android.communicationDevice from setSystemOptions() again.
Use getCommunicationDevice() to observe the route Android selected. routeChange events fire only during a session.
getCommunicationDevice Android 12+ (API 31)
Returns the device Android currently selected for communication, including an accessory chosen by the system. It does not return the requested preference.
Returns Promise<AudioDeviceInfo | null>, which resolves with null below Android 12 (API 31).
On iOS and web both calls are no-op.
androidInputPreset: 'voiceCommunication' on AudioRecorder requests the Android capture path. androidOutputProfile: 'voiceCommunication' on AudioContext classifies Oboe playback as voice communication. android: { mode: 'inCommunication' } in setSystemOptions owns Android focus, mode, and communication-device routing. These APIs request platform voice-processing facilities; acoustic echo cancellation, noise suppression, and automatic gain control remain device- and route-dependent.
disableSessionManagement iOS
Returns undefined.
Disables all internal default AVAudioSession configurations and management done by the react-native-audio-api package. After calling this method, user is responsible for managing audio session entirely on their own.
Typical use-case for this method is when user wants to fully control audio session outside of react-native-audio-api package,
commonly when using another audio library along react-native-audio-api. The method has to be called before AudioContext is created, for example in app initialization code.
Any later call to setSystemOptions or setAudioSessionActivity will re-enable internal audio session management.
getDevicePreferredSampleRate
Returns number.
observeAudioInterruptions
| Parameter | Type | Description |
|---|---|---|
param | AudioFocusType | boolean | null | It is used to enable/disable observing audio interruptions. Passing false or null disables the observation, otherwise it is enabled. |
On Android, passing an AudioFocusType requests the matching native audio focus mode (for example, 'gain' for long-term playback).
Follow Android's audio focus guidelines for the best user experience.
On iOS, passing true or false only enables or disables interruption event emission; the focus type is ignored.
Returns undefined.
activelyReclaimSession iOS Experimental
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | It is used to enable/disable session spoofing. |
Returns undefined.
Tries more aggressively to reactivate the audio session during interruptions.
In some cases (depends on app session settings and other apps using audio) the system may never
send the interruption ended event. This method checks whether any other audio is playing
and tries to reactivate the audio session as soon as there is "silence", although this might change the expected behavior.
Internally, the method uses AVAudioSessionSilenceSecondaryAudioHintNotification as well as
interval polling to check if other audio is playing.
getSystemVolume
Reads the current system output volume as a 0..1 fraction of its maximum.
Returns number.
observeVolumeChanges
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | It is used to enable/disable observing volume changes. |
On iOS, volume changes are reported only while the audio session is active.
Volume observation does not work on the iOS Simulator. Test it on a physical device.
In React components, the useSystemVolume hook enables the observation and subscribes to the event for you.
Returns undefined.
addSystemEventListener
Adds a callback to be invoked upon hearing an event.
| Parameter | Type | Description |
|---|---|---|
name | SystemEventName | Name of an event listener. |
callback | SystemEventCallback | Callback that will be invoked upon hearing an event. |
Returns AudioEventSubscription if enabled is set to true, undefined otherwise.
requestRecordingPermissions
Brings up the system microphone permissions pop-up on demand. The pop-up automatically shows if microphone data is directly requested, but sometimes it is better to ask beforehand.
Throws an error if there is no NSMicrophoneUsageDescription entry in Info.plist.
Returns Promise<PermissionStatus>, which is resolved after receiving the answer from the system.
checkRecordingPermissions
Checks if recording permissions were previously granted.
Returns Promise<PermissionStatus>, which is resolved after receiving the answer from the system.
requestNotificationPermissions
Brings up the system notification permissions pop-up on demand. The pop-up automatically shows if notification data is directly requested, but sometimes it is better to ask beforehand.
Returns Promise<PermissionStatus>, which is resolved after receiving the answer from the system.
checkNotificationPermissions
Checks if notification permissions were previously granted.
Returns Promise<PermissionStatus>, which is resolved after receiving the answer from the system.
getDevicesInfo
Checks currently used and available devices.
On Android, currentInputs reports the device a recording in progress captures from, a routeChange event with reason ConfigurationChange fires whenever that device changes, including when the recording stops. While nothing is recording it reports the selected device, or nothing when no device is selected, since the platform does not report which input it would pick. currentOutputs is always empty on Android.
Returns Promise<AudioDevicesInfo>, which is resolved after receiving the answer from the system.
setInputDevice
Selects the device that audio is captured from, using an id taken from getDevicesInfo().availableInputs.
| Name | Type | Description |
|---|---|---|
deviceId | string | 'default' | Identifier of the input device to capture from. 'default' drops the selection, so the system chooses the input again. |
A recording in progress moves to the new input and keeps writing the same file.
On Android, a recorder with no device selected uses the first external microphone connected, in this order: USB microphone or audio interface, USB headset, wired headset, Bluetooth headset. Using a Bluetooth headset's microphone on Android 11 and below requires the android.permission.MODIFY_AUDIO_SETTINGS permission; without it such a recorder records from the phone's microphone, and starting one with a Bluetooth microphone explicitly selected fails.
Some USB microphones also expose a headphone output, which the platform then prefers over wired or Bluetooth headphones. To record from such a microphone and hear playback on headphones, connect the microphone first and the headphones after it.
Returns Promise<void>, resolved once the device is selected and rejected when the device cannot be found or when the system fails to switch to it. A rejected call leaves the previous selection in place.
Remarks
Resume recording after an interruption iOS
After the app has been interrupted by, for example a phone call, it is possible to resume an audio recording while the app is still backgrounded. It is impossible to start a new recording session from the background. Due to iOS policies and privacy features, the app has to be configured appropriately first:
- Ensure the session options (set via
setSystemOptions) allow recording and make the app resilient to interruptions from other apps. Refer to the session configuration guidelines. The following settings are a useful starting point:ios.categoryset torecordorplayAndRecord, so the session can record. These categories also allow background recording. An incompatible category leads to acannotStartPlayingerror.ios.modeset todefault.ios.optionsincludemixWithOthers, so the system can mix this session with audio from active sessions in other apps. Trying to resume recording in the background with a non-mixable session leads tocannotInterruptOthers.
- The app must declare background audio mode.
Even if background interruption recovery is unsuccessful, the library retries with a best-effort strategy when the app returns to the foreground after a failed resume.
Types
AudioFocusType


Type definitions
type AudioFocusType =
| 'gain'
| 'gainTransient'
| 'gainTransientExclusive'
| 'gainTransientMayDuck';
SystemOptions


Type definitions
type IOSCategory =
| 'ambient'
| 'multiRoute'
| 'playAndRecord'
| 'playback'
| 'record'
| 'soloAmbient';
type IOSMode =
| 'default'
| 'dualRoute'
| 'gameChat'
| 'measurement'
| 'moviePlayback'
| 'shortFormVideo'
| 'spokenAudio'
| 'videoChat'
| 'videoRecording'
| 'voiceChat'
| 'voicePrompt';
type IOSOption =
| 'allowAirPlay'
| 'allowBluetoothA2DP'
| 'allowBluetoothHFP'
| 'bluetoothHighQualityRecording'
| 'defaultToSpeaker'
| 'duckOthers'
| 'farFieldInput'
| 'interruptSpokenAudioAndMixWithOthers'
| 'mixWithOthers'
| 'overrideMutedMicrophoneInterruption';
interface IOSSystemOptions {
category?: IOSCategory;
mode?: IOSMode;
options?: IOSOption[];
allowHaptics?: boolean;
// Has no effect when using PlaybackNotificationManager as it takes over the "Now playing" controls
notifyOthersOnDeactivation?: boolean;
}
interface AndroidSystemOptions {
mode?: 'inCommunication';
communicationDevice?: CommunicationDevice;
}
interface SystemOptions {
ios?: IOSSystemOptions; // ignored on Android
android?: AndroidSystemOptions; // ignored on iOS
}
Configuration guidelines
Each string union maps directly to the corresponding Apple type:
IOSCategorymaps toAVAudioSession.CategoryIOSModemaps toAVAudioSession.ModeIOSOptionmaps toAVAudioSession.CategoryOptions
Not all ios.options are compatible with every ios.category. Passing an invalid combination to the native API (for example, explicitly setting allowBluetoothA2DP alongside the playback category) will cause the configuration to fail. This can result in a SessionActivationError and total audio silence.
Always verify valid category and option combinations in Apple's AVAudioSession Documentation.
CommunicationDevice


Type definitions
type CommunicationDevice = 'speaker' | 'earpiece' | 'systemDefault';
SystemEventName


Type definitions
interface EventEmptyType {}
interface EventTypeWithValue {
value: number;
}
interface OnInterruptionEventType {
type: 'ended' | 'began'; // if the interruption event has started or ended
shouldResume: boolean; // if the interruption was temporary and we can resume the playback/recording
}
interface OnRouteChangeEventType {
reason:
| 'Unknown'
| 'Override'
| 'CategoryChange'
| 'WakeFromSleep'
| 'NewDeviceAvailable'
| 'OldDeviceUnavailable'
| 'ConfigurationChange'
| 'NoSuitableRouteForCategory';
}
type SystemEvents = {
volumeChange: EventTypeWithValue;
interruption: OnInterruptionEventType;
duck: EventEmptyType;
routeChange: OnRouteChangeEventType;
};
type SystemEventName = keyof SystemEvents;
SystemEventCallback


Type definitions
type SystemEventCallback<Name extends SystemEventName> = (
event: SystemEvents[Name]
) => void;
AudioEventSubscription


Type definitions
interface AudioEventSubscription {
/** @internal */
public readonly subscriptionId: string;
public remove(): void; // used to remove the subscription
}
PermissionStatus


Type definitions
type PermissionStatus = 'Undetermined' | 'Denied' | 'Granted';
AudioDeviceInfo


Type definitions
export interface AudioDeviceInfo {
id: string; // unique device identifier
name: string; // human-readable device name
category: string; // device category (e.g. "Built-In Microphone", "Bluetooth")
}
AudioDevicesInfo


Type definitions
export type AudioDeviceList = AudioDeviceInfo[];
export interface AudioDevicesInfo {
availableInputs: AudioDeviceList;
availableOutputs: AudioDeviceList;
currentInputs: AudioDeviceList;
currentOutputs: AudioDeviceList; // iOS
}