@capawesome/capacitor-audio-session

中文文档
0.1.2发布于 2026/09/02MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1万

Capacitor plugin to configure and observe the iOS audio session.

原始使用文档
文档目录36 节
  1. Features
  2. Use Cases
  3. Compatibility
  4. Installation
  5. Configuration
  6. Usage
  7. Configure the audio session
  8. Activate or deactivate the audio session
  9. Read the current audio outputs
  10. Route playback to the built-in speaker
  11. Listen for interruptions
  12. Listen for route changes
  13. Remove all listeners
  14. API
  15. configure(...)
  16. getCurrentOutputs()
  17. overrideOutput(...)
  18. setActive(...)
  19. addListener('interruption', ...)
  20. addListener('routeChange', ...)
  21. removeAllListeners()
  22. Interfaces
  23. Type Aliases
  24. Session Ownership
  25. FAQ
  26. How is this plugin different from other similar plugins?
  27. Is this plugin available on Android or the Web?
  28. Why are my audio session settings overridden by other plugi…
  29. How can my app play audio without interrupting other apps?
  30. How do I resume playback after a phone call interrupted my …
  31. How do I route audio to the loudspeaker?
  32. Can I use this plugin with Ionic, React, Vue or Angular?
  33. Related Plugins
  34. Newsletter
  35. Changelog
  36. License

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 playback category 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 VersionCapacitor VersionStatus
0.x.x>=8.x.xActive 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-plugins

Then 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 sync

This 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(...)

configure(options: ConfigureOptions) => Promise<void>

Configure the audio session category, mode and options.

Only available on iOS.

ParamType
optionsConfigureOptions

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.

ParamType
optionsOverrideOutputOptions

Since: 0.1.0


setActive(...)

setActive(options: SetActiveOptions) => Promise<void>

Activate or deactivate the audio session.

Only available on iOS.

ParamType
optionsSetActiveOptions

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.

ParamType
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.

ParamType
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

PropTypeDescriptionDefaultSince
categoryAudioSessionCategoryThe audio session category.0.1.0
modeAudioSessionModeThe audio session mode.'default'0.1.0
optionsAudioSessionCategoryOptionsThe audio session category options.0.1.0

AudioSessionCategoryOptions

PropTypeDescriptionDefaultSince
allowAirPlaybooleanWhether AirPlay devices can be used for output.false0.1.0
allowBluetoothbooleanWhether Bluetooth hands-free devices can be used for input and output.false0.1.0
allowBluetoothA2DPbooleanWhether Bluetooth A2DP devices can be used for output.false0.1.0
defaultToSpeakerbooleanWhether audio is routed to the built-in speaker instead of the receiver when no other audio route is connected.false0.1.0
duckOthersbooleanWhether audio from other sessions is reduced in volume (ducked) while audio from this session plays.false0.1.0
interruptSpokenAudioAndMixWithOthersbooleanWhether audio from other sessions using the spokenAudio mode is interrupted and audio from this session is mixed with the remaining audio.false0.1.0
mixWithOthersbooleanWhether audio from this session mixes with audio from other active sessions instead of interrupting them.false0.1.0

GetCurrentOutputsResult

PropTypeDescriptionSince
outputsAudioSessionOutput[]The audio outputs of the current audio route.0.1.0

AudioSessionOutput

PropTypeDescriptionSince
portNamestringThe human-readable name of the audio output port.0.1.0
portTypestringThe type of the audio output port.0.1.0

OverrideOutputOptions

PropTypeDescriptionSince
typeOverrideOutputTypeThe audio output port to route playback to.0.1.0

SetActiveOptions

PropTypeDescriptionDefaultSince
activebooleanWhether the audio session should be activated (true) or deactivated (false).0.1.0
notifyOthersOnDeactivationbooleanWhether other audio sessions are notified when this session is deactivated, so they can resume playback.true0.1.0

PluginListenerHandle

PropType
remove() => Promise<void>

InterruptionEvent

PropTypeDescriptionSince
shouldResumebooleanWhether playback should resume after the interruption ended. Only true if type is ended.0.1.0
typeInterruptionTypeThe type of the interruption.0.1.0

RouteChangeEvent

PropTypeDescriptionSince
outputsAudioSessionOutput[]The audio outputs of the audio route after the change.0.1.0
reasonRouteChangeReasonThe 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.

  • 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.

版本与发布记录

@capawesome/capacitor-audio-session 共发布 4 个版本,首次发布于 2026/07/07;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.2latest2026/09/022 个月前
0.1.12026/07/153 个月前
0.1.02026/07/143 个月前
0.0.12026/07/074 个月前

关于 @capawesome/capacitor-audio-session 的常见问题

@capawesome/capacitor-audio-session 是什么?

Capacitor plugin to configure and observe the iOS audio session.

如何安装 @capawesome/capacitor-audio-session?

在项目目录运行 npm install @capawesome/capacitor-audio-session,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capawesome/capacitor-audio-session 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capawesome/capacitor-audio-session 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capawesome/capacitor-audio-session 可以商用吗?

@capawesome/capacitor-audio-session 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@capawesome/capacitor-audio-session 的下载量有多少?

根据 npm 官方下载统计,@capawesome/capacitor-audio-session 在 2026/10/09 – 2026/11/07 这 30 天内被下载 10,254 次,日均约 342 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capawesome/capacitor-audio-session 还在维护吗?

最新版本 0.1.2 发布于 2026/09/02(2 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/07/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。