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 only)
AudioManager.setAudioSessionOptions({
iosCategory: 'playback',
iosMode: 'default',
iosOptions: ['defaultToSpeaker', 'allowBluetoothA2DP'],
})
// set info for track to be visible while device is locked
AudioManager.setLockScreenInfo({
title: 'Audio file',
artist: 'Software Mansion',
album: 'Audio API',
duration: 10,
});
useEffect(() => {
// enabling emission of events
AudioManager.enableRemoteCommand('remotePlay', true);
AudioManager.enableRemoteCommand('remotePause', true);
AudioManager.observeAudioInterruptions(true);
// callback to be invoked on 'remotePlay' event
const remotePlaySubscription = AudioManager.addSystemEventListener(
'remotePlay',
(event) => {
console.log('remotePlay event:', event);
}
);
// callback to be invoked on 'remotePause' event
const remotePauseSubscription = AudioManager.addSystemEventListener(
'remotePause',
(event) => {
console.log('remotePause event:', event);
}
);
// callback to be invoked on 'interruption' event
const interruptionSubscription = AudioManager.addSystemEventListener(
'interruption',
(event) => {
console.log('Interruption event:', event);
}
);
AudioManager.getDevicesInfo().then(console.log);
return () => {
remotePlaySubscription?.remove();
remotePauseSubscription?.remove();
interruptionSubscription?.remove();
};
}, []);
}
Methods
setAudioSessionOptions iOS only
| Parameter | Type | Description |
|---|---|---|
| options | SessionOptions | Options to be set for AVAudioSession |
Returns undefined
setAudioSessionActivity iOS only
| Parameter | Type | Description |
|---|---|---|
| enabled | boolean | It is used to set/unset AVAudioSession activity |
Returns promise of boolean type, which is resolved to true if invokation ended with success, false otherwise.'
disableSessionManagement iOS only
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
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | It is used to enable/disable observing audio interruptions |
Returns undefined
activelyReclaimSession iOS only Experimental
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | It is used to enable/disable session spoofing |
Returns undefined
More aggressively try to reactivate the audio session during interruptions.
In some cases (depends on app session settings and other apps using audio) system may never
send the interruption ended event. This method will check if any other audio is playing
and try to reactivate the audio session, as soon as there is "silence".
Although this might change the expected behavior.
Internally method uses AVAudioSessionSilenceSecondaryAudioHintNotification as well as
interval polling to check if other audio is playing.
observeVolumeChanges
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | It is used to enable/disable observing volume changes |
Returns undefined
addSystemEventListener
Adds 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 of PermissionStatus type, which is resolved after receiving answer from the system.
checkRecordingPermissions
Checks if permissions were previously granted.
Throws an error if there is no NSMicrophoneUsageDescription entry in Info.plist
Returns promise of PermissionStatus type, which is resolved after receiving 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 of PermissionStatus type, which is resolved after receiving answer from the system.
checkRecordingPermissions
Checks if permissions were previously granted.
Returns promise of PermissionStatus type, which is resolved after receiving answer from the system.
getDevicesInfo
Checks currently used and available devices.
Returns promise of AudioDevicesInfo type, which is resolved after receiving answer from the system.
Remarks
SessionOptions
Type definitions
type IOSCategory =
| 'record'
| 'ambient'
| 'playback'
| 'multiRoute'
| 'soloAmbient'
| 'playAndRecord';
type IOSMode =
| 'default'
| 'gameChat'
| 'videoChat'
| 'voiceChat'
| 'measurement'
| 'voicePrompt'
| 'spokenAudio'
| 'moviePlayback'
| 'videoRecording';
type IOSOption =
| 'duckOthers'
| 'allowAirPlay'
| 'mixWithOthers'
| 'allowBluetooth'
| 'defaultToSpeaker'
| 'allowBluetoothA2DP'
| 'overrideMutedMicrophoneInterruption'
| 'interruptSpokenAudioAndMixWithOthers';
interface SessionOptions {
iosMode?: IOSMode;
iosOptions?: IOSOption[];
iosCategory?: IOSCategory;
}
SystemEventName | RemoteCommandEventName
Type definitions
interface EventEmptyType {}
interface EventTypeWithValue {
value: number;
}
interface OnInterruptionEventType {
type: 'ended' | 'began'; // if 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';
}
interface AudioAPIEvents {
ended: OnEndedEventType;
loopEnded: EventEmptyType;
audioReady: OnAudioReadyEventType;
positionChanged: EventTypeWithValue;
audioError: EventEmptyType;
systemStateChanged: EventEmptyType;
}
// For `NotificationEvents` see PlaybackNotificationManager docs
type AudioEvents = SystemEvents & AudioAPIEvents & NotificationEvents;
type RemoteCommandEventName = keyof RemoteCommandEvents;
type SystemEventName = keyof SystemEvents;
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';
AudioDevicesInfo
Type definitions
export interface AudioDeviceInfo {
name: string;
category: string;
}
export type AudioDeviceList = AudioDeviceInfo[];
export interface AudioDevicesInfo {
availableInputs: AudioDeviceList;
availableOutputs: AudioDeviceList;
currentInputs: AudioDeviceList; // iOS only
currentOutputs: AudioDeviceList; // iOS only
}