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.

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.

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.

Returns Promise<AudioDevicesInfo>, which is resolved after receiving the answer from the system.

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; // iOS
currentOutputs: AudioDeviceList; // iOS
}