快速入门
复制包含安装步骤和该插件完整 Markdown 指南的配置 prompt。
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-native-audio`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/native-audio/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
安装
“安装”章节你可以使用我们的 AI 辅助设置来安装插件。使用以下命令将 Capgo skills 添加到你的 AI 工具中:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins然后使用以下 prompt:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-native-audio` plugin in my project.如果你更想手动设置,请运行以下命令安装插件,并按照下方各平台的说明操作:
bun add @capgo/capacitor-native-audiobunx cap sync导入
“导入”章节import { NativeAudio } from '@capgo/capacitor-native-audio';快速入门
章节标题为“快速入门”只需一次配置,即可预加载音频片段并播放 UI 反馈音效 playOnce() 实现“即发即忘”的音效播放。
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.configure({ focus: true, showNotification: false });await NativeAudio.playOnce({ assetPath: 'public/sounds/tap.mp3', volume: 0.8 });示例:音乐风格会话
标题为“示例:音乐风格会话”await NativeAudio.preload({ assetId: 'episode-1', assetPath: 'https://cdn.example.com/episode.m3u8', isUrl: true,});await NativeAudio.play({ assetId: 'episode-1' });await NativeAudio.addListener('currentTime', ({ assetId, time }) => updateScrubber(assetId, time));示例:释放音频会话
示例:释放音频会话当其他插件需要独占音频控制权时,请停止播放并调用 deinitPlugin() 以恢复之前的会话。
await NativeAudio.stop({ assetId: 'episode-1' });await NativeAudio.deinitPlugin();常见坑点
章节标题为“常见陷阱”- 正在播放 vs 混音:
showNotification: true在 iOS 上会切换到播放类别,从而中断背景音乐。 - Android 后台: 启用
backgroundPlayback仅在您根据 README 启动了必要的 {foreground service} 和权限后才有效。 - Web 端监听器:Web 端不会发出播放状态监听事件;请对依赖这些事件的 UI 做好防护。
API 概览
章节标题:“API 概览”configure
章节标题:“configure”配置音频播放器
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.configure({ focus: false, background: false, ignoreSilent: false, showNotification: false, backgroundPlayback: false,});preload
章节标题:“preload”加载音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.preload({ assetPath: 'path/to/file', assetId: 'asset-id-123',});playOnce
章节标题:“playOnce”播放一次音频文件并自动清理
专为简单的单次音频播放设计的模式, 例如通知音、UI 反馈或其他无需手动管理状态的 短音频片段。
核心功能:
- 即发即弃 (Fire-and-forget): 无需手动预加载、播放、停止或卸载
- 自动清理: 音频资源在播放完成后会自动卸载
- 可选的文件删除功能: 播放后可删除本地文件(适用于临时文件)
- 返回 assetId: 如有需要,仍可控制播放(暂停、停止等)
使用场景:
- 通知音
- UI 音效(按钮点击、提示音)
- 只播放一次的短音频片段
- 需要清理的临时音频文件
与常规 play() 的对比:
play(): 需要手动执行 preload、play 和 unload 步骤playOnce(): 只需调用一次即可自动处理所有流程
import { NativeAudio } from '@capgo/capacitor-native-audio';
// Simple one-shot playbackawait NativeAudio.playOnce({ assetPath: 'audio/notification.mp3' });
// Play and delete the file after completionawait NativeAudio.playOnce({ assetPath: 'file:///path/to/temp/audio.mp3', isUrl: true, deleteAfterPlay: true});
// Get the assetId to control playbackconst { assetId } = await NativeAudio.playOnce({ assetPath: 'audio/long-track.mp3', autoPlay: true});// Later, you can stop it manually if neededawait NativeAudio.stop({ assetId });isPreloaded
标题为“isPreloaded”的章节检查音频文件是否已预加载
import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.isPreloaded({ assetPath: 'path/to/file', assetId: 'asset-id-123',});console.log(result);play
标题为 “play” 的章节播放音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.play({ assetId: 'asset-id-123' });pause
标题为“pause”的章节暂停音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.pause({ assetId: 'asset-id-123' });resume
标题为“resume”的章节恢复音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.resume({ assetId: 'asset-id-123' });loop
“loop”章节停止音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.loop({ assetId: 'asset-id-123' });stop
标题为“stop”的章节停止音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.stop({ assetId: 'asset-id-123' });unload
“unload” 章节卸载音频文件
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.unload({ assetId: 'asset-id-123' });setVolume
标题为“setVolume”的章节设置音频文件音量
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setVolume({ assetId: 'asset-id-123', volume: 0.5,});setRate
“setRate” 章节设置音频文件播放速率
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setRate({ assetId: 'asset-id-123', rate: 1,});setCurrentTime
“setCurrentTime” 章节设置音频文件当前播放时间
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setCurrentTime({ assetId: 'asset-id-123', time: 10,});getCurrentTime
“getCurrentTime” 章节获取音频文件的当前播放时间
import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.getCurrentTime({ assetId: 'asset-id-123' });console.log(result);getDuration
“getDuration” 章节获取音频文件的时长(秒)
import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.getDuration({ assetId: 'asset-id-123' });console.log(result);isPlaying
“isPlaying” 章节检查音频文件是否正在播放
import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.isPlaying({ assetId: 'asset-id-123' });console.log(result);clearCache
“clearCache” 章节清除远程音频文件的缓存
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.clearCache();setDebugMode
“setDebugMode” 章节设置调试模式日志
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setDebugMode({ enabled: true });deinitPlugin
“deinitPlugin” 章节反初始化插件并恢复原始音频会话设置 此方法会停止所有正在播放的音频,并撤销插件所做的任何音频会话更改 当需要确保与其他音频插件的兼容性时,请使用此方法
import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.deinitPlugin();类型参考
“类型参考” 章节ConfigureOptions
“ConfigureOptions” 章节export interface ConfigureOptions { /** * focus the audio with Audio Focus */ focus?: boolean; /** * Play the audio in the background */ background?: boolean; /** * Ignore silent mode, works only on iOS setting this will nuke other audio apps */ ignoreSilent?: boolean; /** * Show audio playback in the notification center (iOS and Android) * When enabled, displays audio metadata (title, artist, album, artwork) in the system notification * and Control Center (iOS) or lock screen. * * **Important iOS Behavior:** * Enabling this option changes the audio session category to `.playback` with `.default` mode, * which means your app's audio will **interrupt** other apps' audio (like background music from * Spotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing * info to appear in Control Center and on the lock screen. * * **Trade-offs:** * - `showNotification: true` → Shows Now Playing controls, but interrupts other audio * - `showNotification: false` → Audio mixes with other apps, but no Now Playing controls * * Use this when your app is the primary audio source (music players, podcast apps, etc.). * Disable this for secondary audio like sound effects or notification sounds where mixing * with background music is preferred. * * @see https://github.com/Cap-go/capacitor-native-audio/issues/202 */ showNotification?: boolean; /** * Enable background audio playback (Android only) * * When enabled, audio will continue playing when the app is backgrounded or the screen is locked. * The plugin will skip the automatic pause/resume logic that normally occurs when the app * enters the background or returns to the foreground. * * **Important Android Requirements:** * To use background playback on Android, your app must: * 1. Declare the required permissions in `AndroidManifest.xml`: * - `<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />` * - `<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />` * - `<uses-permission android:name="android.permission.WAKE_LOCK" />` * 2. Start a Foreground Service with a media-style notification before backgrounding * (the plugin does not automatically create or manage the foreground service) * 3. Use `showNotification: true` to display playback controls in the notification * * **Usage Example:** * ```typescript * await NativeAudio.configure({ * backgroundPlayback: true, * showNotification: true * }); * // Start your foreground service here * // Then preload and play audio as normal * ``` * * @default false * @platform Android * @since 8.2.0 */ backgroundPlayback?: boolean;}PreloadOptions
“PreloadOptions” 章节export interface PreloadOptions { /** * Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://) * Supported formats: * - MP3, WAV (all platforms) * - M3U8/HLS streams (iOS and Android) */ assetPath: string; /** * Asset Id, unique identifier of the file */ assetId: string; /** * Volume of the audio, between 0.1 and 1.0 */ volume?: number; /** * Audio channel number, default is 1 */ audioChannelNum?: number; /** * Is the audio file a URL, pass true if assetPath is a `file://` url * or a streaming URL (m3u8) */ isUrl?: boolean; /** * Metadata to display in the notification center when audio is playing. * Only used when `showNotification: true` is set in `configure()`. * * See {@link ConfigureOptions.showNotification} for important details about * how this affects audio mixing behavior on iOS. * * @see NotificationMetadata */ notificationMetadata?: NotificationMetadata; /** * Custom HTTP headers to include when fetching remote audio files. * Only used when isUrl is true and assetPath is a remote URL (http/https). * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' } * * @since 7.10.0 */ headers?: Record<string, string>;}PlayOnceOptions
“PlayOnceOptions” 章节export interface PlayOnceOptions { /** * Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://) * Supported formats: * - MP3, WAV (all platforms) * - M3U8/HLS streams (iOS and Android) */ assetPath: string; /** * Volume of the audio, between 0.1 and 1.0 * @default 1.0 */ volume?: number; /** * Is the audio file a URL, pass true if assetPath is a `file://` url * or a streaming URL (m3u8) * @default false */ isUrl?: boolean; /** * Automatically start playback after loading * @default true */ autoPlay?: boolean; /** * Delete the audio file from disk after playback completes * Only works for local files (file:// URLs), ignored for remote URLs * @default false * @since 7.11.0 */ deleteAfterPlay?: boolean; /** * Metadata to display in the notification center when audio is playing. * Only used when `showNotification: true` is set in `configure()`. * * See {@link ConfigureOptions.showNotification} for important details about * how this affects audio mixing behavior on iOS. * * @see NotificationMetadata * @since 7.10.0 */ notificationMetadata?: NotificationMetadata; /** * Custom HTTP headers to include when fetching remote audio files. * Only used when isUrl is true and assetPath is a remote URL (http/https). * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' } * * @since 7.10.0 */ headers?: Record<string, string>;}PlayOnceResult
“PlayOnceResult” 章节export interface PlayOnceResult { /** * The internally generated asset ID for this playback * Can be used to control playback (pause, stop, etc.) before completion */ assetId: string;}AssetPlayOptions
“AssetPlayOptions” 章节export interface AssetPlayOptions { /** * Asset Id, unique identifier of the file */ assetId: string; /** * Time to start playing the audio, in seconds */ time?: number; /** * Delay to start playing the audio, in seconds */ delay?: number;
/** * Volume of the audio, between 0.1 and 1.0 */ volume?: number;
/** * Whether to fade in the audio */ fadeIn?: boolean;
/** * Whether to fade out the audio */ fadeOut?: boolean;
/** * Fade in duration in seconds. * Only used if fadeIn is true. * Default is 1s. */ fadeInDuration?: number;
/** * Fade out duration in seconds. * Only used if fadeOut is true. * Default is 1s. */ fadeOutDuration?: number;
/** * Time in seconds from the start of the audio to start fading out. * Only used if fadeOut is true. * Default is fadeOutDuration before end of audio. */ fadeOutStartTime?: number;}AssetPauseOptions
“AssetPauseOptions” 章节export interface AssetPauseOptions { /** * Asset Id, unique identifier of the file */ assetId: string;
/** * Whether to fade out the audio before pausing */ fadeOut?: boolean;
/** * Fade out duration in seconds. * Default is 1s. */ fadeOutDuration?: number;}AssetResumeOptions
“AssetResumeOptions” 章节export interface AssetResumeOptions { /** * Asset Id, unique identifier of the file */ assetId: string;
/** * Whether to fade in the audio during resume */ fadeIn?: boolean;
/** * Fade in duration in seconds. * Default is 1s. */ fadeInDuration?: number;}Assets
“Assets” 章节export interface Assets { /** * Asset Id, unique identifier of the file */ assetId: string;}AssetStopOptions
“AssetStopOptions” 章节export interface AssetStopOptions { /** * Asset Id, unique identifier of the file */ assetId: string;
/** * Whether to fade out the audio before stopping */ fadeOut?: boolean;
/** * Fade out duration in seconds. * Default is 1s. */ fadeOutDuration?: number;}AssetVolume
“AssetVolume” 章节export interface AssetVolume { /** * Asset Id, unique identifier of the file */ assetId: string; /** * Volume of the audio, between 0.1 and 1.0 */ volume: number; /** * Time over which to fade to the target volume, in seconds. Default is 0s (immediate). */ duration?: number;}AssetRate
“AssetRate” 章节export interface AssetRate { /** * Asset Id, unique identifier of the file */ assetId: string; /** * Rate of the audio, between 0.1 and 1.0 */ rate: number;}AssetSetTime
“AssetSetTime” 章节export interface AssetSetTime { /** * Asset Id, unique identifier of the file */ assetId: string; /** * Time to set the audio, in seconds */ time: number;}单一事实来源
标题为“单一事实来源”的部分本页面由插件的 src/definitions.ts生成。当上游的公共 API 发生变化时,请重新运行 sync。
从入门指南继续
“从入门指南继续”章节如果你正在使用 快速入门 来规划原生媒体和界面行为,并将其与 使用 @capgo/capacitor-native-audio 关于使用 @capgo/capacitor-native-audio 中的原生能力, 使用 @capgo/capacitor-live-activities 用于使用 @capgo/capacitor-live-activities 时的原生能力, @capgo/capacitor-live-activities 在 @capgo/capacitor-live-activities 中的实现细节, 使用 @capgo/capacitor-video-player 有关使用 @capgo/capacitor-video-player 时的原生能力,以及 @capgo/capacitor-video-player 关于 @capgo/capacitor-video-player. 中的实现细节