Skip to main content
Version: Next

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.setAudioSessionOptions({
iosCategory: 'playback',
iosMode: 'default',
iosOptions: ['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​

setAudioSessionOptions
iOS
​

AVAudioSession Compatibility

Not all iosOptions are compatible with every iosCategory. 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.

ParameterTypeDescription
optionsSessionOptionsOptions to be set for AVAudioSession.

Returns undefined.​

setAudioSessionActivity
iOS
​

ParameterTypeDescription
enabledbooleanIt is used to set/unset AVAudioSession activity.

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.

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 setAudioSessionOptions or setAudioSessionActivity will re-enable internal audio session management.

getDevicePreferredSampleRate​

Returns number.​

observeAudioInterruptions​

ParameterTypeDescription
paramAudioFocusType | boolean | nullIt is used to enable/disable observing audio interruptions. Passing false or null disables the observation, otherwise it is enabled.
info

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
​

ParameterTypeDescription
enabledbooleanIt 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​

ParameterTypeDescription
enabledbooleanIt is used to enable/disable observing volume changes.
info

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.

ParameterTypeDescription
nameSystemEventNameName of an event listener.
callbackSystemEventCallbackCallback 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.

NameTypeDescription
deviceIdstring | '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.

tip

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​

AudioFocusType​

Type definitions

type AudioFocusType =
| 'gain'
| 'gainTransient'
| 'gainTransientExclusive'
| 'gainTransientMayDuck';

SessionOptions​

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 SessionOptions {
iosMode?: IOSMode;
iosOptions?: IOSOption[];
iosCategory?: IOSCategory;
iosAllowHaptics?: boolean;
// Has no effect when using PlaybackNotificationManager as it takes over the "Now playing" controls
iosNotifyOthersOnDeactivation?: boolean;
}

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
}