@capawesome/capacitor-audio-session
v0.1.1
Published
Capacitor plugin to configure and observe the iOS audio session.
Maintainers
Readme
Capacitor Audio Session Plugin
Capacitor plugin to configure and observe the iOS audio session.
Features
The Capacitor Audio Session plugin is one of the most complete audio session management solutions for Capacitor apps. Here are some of the key features:
- 🎛️ Configuration: Set the audio session category, mode and options.
- 🔌 Activation: Activate and deactivate the audio session.
- 🔊 Output routing: Read the current audio outputs and override the output port.
- 📡 Events: Observe interruption and route change events.
- 🤝 Compatibility: Works alongside the Audio Player and Audio Recorder plugins.
- 📦 CocoaPods & SPM: Supports CocoaPods and Swift Package Manager for iOS.
- 🔁 Up-to-date: Always supports the latest Capacitor version.
Missing a feature? Just open an issue and we'll take a look!
Use Cases
The Audio Session plugin is typically used whenever an app needs fine-grained control over how audio behaves on iOS, for example:
- Media playback apps: Configure the
playbackcategory so audio keeps playing while other apps are silenced. - Voice and video chat: Switch between the receiver and the built-in speaker using the output override.
- Mixing with other apps: Let your audio play alongside (or duck) audio from other apps using the category options.
- Handling phone calls: Pause playback when the session is interrupted and resume it when the interruption ends.
- Headphone awareness: React when headphones or Bluetooth devices are plugged in or out by observing route changes.
Compatibility
| Plugin Version | Capacitor Version | Status | | -------------- | ----------------- | -------------- | | 0.x.x | >=8.x.x | Active support |
Installation
You can use our AI-Assisted Setup to install the plugin. Add the Capawesome Skills to your AI tool using the following command:
npx skills add capawesome-team/skills --skill capacitor-pluginsThen use the following prompt:
Use the `capacitor-plugins` skill from `capawesome-team/skills` to install the `@capawesome/capacitor-audio-session` plugin in my project.If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:
npm install @capawesome/capacitor-audio-session
npx cap syncThis plugin is only available on iOS. On Android and Web, all methods reject as unimplemented.
Configuration
No configuration required for this plugin.
Usage
The following examples show how to configure the audio session, activate or deactivate it, read the current audio outputs, route playback to the built-in speaker, listen for interruptions and route changes, and remove all listeners.
Configure the audio session
Set the audio session category, mode and options, for example for movie playback that interrupts audio from other apps. All methods of this plugin are only available on iOS:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const configure = async () => {
await AudioSession.configure({
category: 'playback',
mode: 'moviePlayback',
options: {
mixWithOthers: false,
},
});
};Activate or deactivate the audio session
Activate the audio session before playing or recording audio, and deactivate it when you are done so that other apps can resume their playback:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const setActive = async () => {
await AudioSession.setActive({ active: true });
};Read the current audio outputs
Get the audio outputs of the current audio route, for example to check whether headphones are connected:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const getCurrentOutputs = async () => {
const { outputs } = await AudioSession.getCurrentOutputs();
return outputs;
};Route playback to the built-in speaker
Override the audio output port that is used for playback, for example to switch from the receiver to the loudspeaker during a call:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const overrideOutput = async () => {
await AudioSession.overrideOutput({ type: 'speaker' });
};Listen for interruptions
Get notified when the audio session is interrupted, e.g. by an incoming phone call. The shouldResume flag tells you whether playback should resume after the interruption ended:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const addInterruptionListener = async () => {
await AudioSession.addListener('interruption', event => {
console.log('Interruption:', event.type, event.shouldResume);
});
};Listen for route changes
Get notified when the audio route changes, e.g. when headphones are plugged in or out:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const addRouteChangeListener = async () => {
await AudioSession.addListener('routeChange', event => {
console.log('Route change:', event.reason, event.outputs);
});
};Remove all listeners
Remove all listeners that were registered for this plugin:
import { AudioSession } from '@capawesome/capacitor-audio-session';
const removeAllListeners = async () => {
await AudioSession.removeAllListeners();
};API
configure(...)getCurrentOutputs()overrideOutput(...)setActive(...)addListener('interruption', ...)addListener('routeChange', ...)removeAllListeners()- Interfaces
- Type Aliases
configure(...)
configure(options: ConfigureOptions) => Promise<void>Configure the audio session category, mode and options.
Only available on iOS.
| Param | Type |
| ------------- | ------------------------------------------------------------- |
| options | ConfigureOptions |
Since: 0.1.0
getCurrentOutputs()
getCurrentOutputs() => Promise<GetCurrentOutputsResult>Get the audio outputs of the current audio route.
Only available on iOS.
Returns: Promise<GetCurrentOutputsResult>
Since: 0.1.0
overrideOutput(...)
overrideOutput(options: OverrideOutputOptions) => Promise<void>Override the audio output port that is used for playback.
Only available on iOS.
| Param | Type |
| ------------- | ----------------------------------------------------------------------- |
| options | OverrideOutputOptions |
Since: 0.1.0
setActive(...)
setActive(options: SetActiveOptions) => Promise<void>Activate or deactivate the audio session.
Only available on iOS.
| Param | Type |
| ------------- | ------------------------------------------------------------- |
| options | SetActiveOptions |
Since: 0.1.0
addListener('interruption', ...)
addListener(eventName: 'interruption', listenerFunc: (event: InterruptionEvent) => void) => Promise<PluginListenerHandle>Called when the audio session is interrupted, e.g. by an incoming phone call.
Only available on iOS.
| Param | Type |
| ------------------ | ----------------------------------------------------------------------------------- |
| eventName | 'interruption' |
| listenerFunc | (event: InterruptionEvent) => void |
Returns: Promise<PluginListenerHandle>
Since: 0.1.0
addListener('routeChange', ...)
addListener(eventName: 'routeChange', listenerFunc: (event: RouteChangeEvent) => void) => Promise<PluginListenerHandle>Called when the audio route changes, e.g. when headphones are plugged in or out.
Only available on iOS.
| Param | Type |
| ------------------ | --------------------------------------------------------------------------------- |
| eventName | 'routeChange' |
| listenerFunc | (event: RouteChangeEvent) => void |
Returns: Promise<PluginListenerHandle>
Since: 0.1.0
removeAllListeners()
removeAllListeners() => Promise<void>Remove all listeners for this plugin.
Only available on iOS.
Since: 0.1.0
Interfaces
ConfigureOptions
| Prop | Type | Description | Default | Since |
| -------------- | ----------------------------------------------------------------------------------- | ----------------------------------- | ---------------------- | ----- |
| category | AudioSessionCategory | The audio session category. | | 0.1.0 |
| mode | AudioSessionMode | The audio session mode. | 'default' | 0.1.0 |
| options | AudioSessionCategoryOptions | The audio session category options. | | 0.1.0 |
AudioSessionCategoryOptions
| Prop | Type | Description | Default | Since |
| ------------------------------------------ | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----- |
| allowAirPlay | boolean | Whether AirPlay devices can be used for output. | false | 0.1.0 |
| allowBluetooth | boolean | Whether Bluetooth hands-free devices can be used for input and output. | false | 0.1.0 |
| allowBluetoothA2DP | boolean | Whether Bluetooth A2DP devices can be used for output. | false | 0.1.0 |
| defaultToSpeaker | boolean | Whether audio is routed to the built-in speaker instead of the receiver when no other audio route is connected. | false | 0.1.0 |
| duckOthers | boolean | Whether audio from other sessions is reduced in volume (ducked) while audio from this session plays. | false | 0.1.0 |
| interruptSpokenAudioAndMixWithOthers | boolean | Whether audio from other sessions using the spokenAudio mode is interrupted and audio from this session is mixed with the remaining audio. | false | 0.1.0 |
| mixWithOthers | boolean | Whether audio from this session mixes with audio from other active sessions instead of interrupting them. | false | 0.1.0 |
GetCurrentOutputsResult
| Prop | Type | Description | Since |
| ------------- | --------------------------------- | --------------------------------------------- | ----- |
| outputs | AudioSessionOutput[] | The audio outputs of the current audio route. | 0.1.0 |
AudioSessionOutput
| Prop | Type | Description | Since |
| -------------- | ------------------- | ------------------------------------------------- | ----- |
| portName | string | The human-readable name of the audio output port. | 0.1.0 |
| portType | string | The type of the audio output port. | 0.1.0 |
OverrideOutputOptions
| Prop | Type | Description | Since |
| ---------- | ----------------------------------------------------------------- | ------------------------------------------- | ----- |
| type | OverrideOutputType | The audio output port to route playback to. | 0.1.0 |
SetActiveOptions
| Prop | Type | Description | Default | Since |
| -------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------- | ----------------- | ----- |
| active | boolean | Whether the audio session should be activated (true) or deactivated (false). | | 0.1.0 |
| notifyOthersOnDeactivation | boolean | Whether other audio sessions are notified when this session is deactivated, so they can resume playback. | true | 0.1.0 |
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
InterruptionEvent
| Prop | Type | Description | Since |
| ------------------ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----- |
| shouldResume | boolean | Whether playback should resume after the interruption ended. Only true if type is ended. | 0.1.0 |
| type | InterruptionType | The type of the interruption. | 0.1.0 |
RouteChangeEvent
| Prop | Type | Description | Since |
| ------------- | --------------------------------------------------------------- | ------------------------------------------------------ | ----- |
| outputs | AudioSessionOutput[] | The audio outputs of the audio route after the change. | 0.1.0 |
| reason | RouteChangeReason | The reason why the audio route changed. | 0.1.0 |
Type Aliases
AudioSessionCategory
The audio session category.
'ambient' | 'multiRoute' | 'playAndRecord' | 'playback' | 'record' | 'soloAmbient'
AudioSessionMode
The audio session mode.
'default' | 'gameChat' | 'measurement' | 'moviePlayback' | 'spokenAudio' | 'videoChat' | 'videoRecording' | 'voiceChat' | 'voicePrompt'
OverrideOutputType
The audio output port to route playback to.
'default' | 'speaker'
InterruptionType
The type of an audio session interruption.
'began' | 'ended'
RouteChangeReason
The reason why the audio route changed.
'categoryChange' | 'newDeviceAvailable' | 'noSuitableRouteForCategory' | 'oldDeviceUnavailable' | 'override' | 'routeConfigurationChange' | 'unknown' | 'wakeFromSleep'
Session Ownership
The audio session returned by AVAudioSession.sharedInstance() is a single, app-wide object. This plugin gives you manual control over it, but so do other audio-related plugins (such as the Audio Player, Audio Recorder and Speech Recognition plugins) and the underlying platform APIs they use.
Because the session is shared, the last write wins: calling configure(...) may override the category, mode or options that another plugin has set, and vice versa. This plugin cannot prevent that. If you combine this plugin with other audio plugins, make sure to reconfigure the session whenever you switch between playback, recording and other audio scenarios.
FAQ
How is this plugin different from other similar plugins?
It gives you fine-grained control over the iOS audio session through one fully typed API: set the category, mode and options, activate or deactivate the session, read the current outputs and override the output route, and observe interruption and route-change events. It documents the shared, app-wide nature of the audio session honestly, so you know exactly how it behaves alongside other audio code, and it's actively maintained against the latest Capacitor and iOS versions. If you only play a simple sound, a basic setup is enough; if you need precise session control, this plugin is designed for exactly that.
Is this plugin available on Android or the Web?
No, this plugin is only available on iOS since it controls the iOS-specific audio session. On Android and Web, all methods reject as unimplemented, so you can safely include the plugin in a cross-platform app.
Why are my audio session settings overridden by other plugins?
The audio session is a single, app-wide object that is shared with other audio-related plugins (such as the Audio Player and Audio Recorder plugins) and the underlying platform APIs they use. The last write wins, so another plugin may override the category, mode or options you have set. Reconfigure the session whenever you switch between playback, recording and other audio scenarios. See the Session Ownership section for more details.
How can my app play audio without interrupting other apps?
Use the mixWithOthers category option when calling configure(...) to mix your audio with audio from other active sessions instead of interrupting them. Alternatively, use the duckOthers option to reduce the volume of other sessions while your audio plays.
How do I resume playback after a phone call interrupted my app?
Add a listener for the interruption event. When the event's type is ended and shouldResume is true, playback should be resumed. See Listen for interruptions for an example.
How do I route audio to the loudspeaker?
Call overrideOutput(...) with the type speaker to route playback to the built-in speaker, and with default to restore the default route. If you want audio to be routed to the speaker by default when no other route is connected, use the defaultToSpeaker category option when calling configure(...).
Can I use this plugin with Ionic, React, Vue or Angular?
Yes, the plugin is framework-agnostic. It works in any Capacitor app regardless of the web framework, including Ionic with Angular, React, or Vue, as well as plain JavaScript projects.
Related Plugins
- Audio Player: Play audio with background support.
- Audio Recorder: Record audio using the device's microphone.
- Media Session: Interact with media controllers, volume keys and media buttons.
- Volume: Control the volume and observe hardware volume button presses.
Newsletter
Stay up to date with the latest news and updates about the Capawesome, Capacitor, and Ionic ecosystem by subscribing to our Capawesome Newsletter.
Changelog
See CHANGELOG.md.
License
See LICENSE.
