跳过内容

开始使用

GitHub

您可以使用我们的AI辅助设置来安装插件。将Capgo技能添加到您的AI工具中,使用以下命令:

终端窗口
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

context:Capgo营销网站。角色:UI标签。见于:页面代理/[slug].astro。消息键`agents_page_copy_label`(代理页面复制标签)。

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-native-audio` plugin in my project.

然后使用以下提示:

终端窗口
npm install @capgo/capacitor-native-audio
npx cap sync

Import

导入
import { NativeAudio } from '@capgo/capacitor-native-audio';

API 简介

API 简介

configure

配置

配置音频播放器

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.configure({
focus: false,
background: false,
ignoreSilent: false,
showNotification: false,
backgroundPlayback: false,
});

preload

上载

加载音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.preload({
assetPath: 'path/to/file',
assetId: 'asset-id-123',
});

playOnce

播放一次

播放一次音频文件,自动清理

方法,用于简单的单次音频播放,例如通知声音、UI反馈或其他不需要手动状态管理的短音频片段。

功能特点:

  • 无需手动预加载、播放、停止或卸载: 无需手动预加载、播放、停止或卸载
  • 自动清理: 资产在播放完成后自动卸载
  • 可选文件删除: 可以在播放完成后删除本地文件(适用于临时文件)
  • 返回 assetId: 可以继续控制播放(暂停、停止等)

使用场景:

  • 通知声音
  • UI 声音效果(按钮点击、警告)
  • 只播放一次的短音频片段
  • 临时音频文件应清理

与普通play()比较:

  • play(): 需要手动预加载、播放和卸载步骤
  • playOnce(): 可以自动处理所有内容仅需一个调用
import { NativeAudio } from '@capgo/capacitor-native-audio';
// Simple one-shot playback
await NativeAudio.playOnce({ assetPath: 'audio/notification.mp3' });
// Play and delete the file after completion
await NativeAudio.playOnce({
assetPath: 'file:///path/to/temp/audio.mp3',
isUrl: true,
deleteAfterPlay: true
});
// Get the assetId to control playback
const { assetId } = await NativeAudio.playOnce({
assetPath: 'audio/long-track.mp3',
autoPlay: true
});
// Later, you can stop it manually if needed
await NativeAudio.stop({ assetId });

检查音频文件是否已预加载

import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.isPreloaded({
assetPath: 'path/to/file',
assetId: 'asset-id-123',
});
console.log(result);

播放音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.play({ assetId: 'asset-id-123' });

暂停音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.pause({ assetId: 'asset-id-123' });

resume

恢复

恢复音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.resume({ assetId: 'asset-id-123' });

loop

循环

循环音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.loop({ assetId: 'asset-id-123' });

循环音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.stop({ assetId: 'asset-id-123' });

unload

停止

卸载音频文件

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.unload({ assetId: 'asset-id-123' });

setVolume

音量设置

设置音频文件的音量

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setVolume({
assetId: 'asset-id-123',
volume: 0.5,
});

设置音频文件的速率

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setRate({
assetId: 'asset-id-123',
rate: 1,
});

设置音频文件的当前时间

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.setCurrentTime({
assetId: 'asset-id-123',
time: 10,
});

获取音频文件的当前时间

import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.getCurrentTime({ assetId: 'asset-id-123' });
console.log(result);

getDuration

获取时长

获取音频文件的时长(秒)

import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.getDuration({ assetId: 'asset-id-123' });
console.log(result);

isPlaying

播放状态

检查音频文件是否正在播放

import { NativeAudio } from '@capgo/capacitor-native-audio';
const result = await NativeAudio.isPlaying({ assetId: 'asset-id-123' });
console.log(result);

clearCache

清除缓存

清除远程音频文件的缓存

import { NativeAudio } from '@capgo/capacitor-native-audio';
await NativeAudio.clearCache();

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

PreloadOptions
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

PlayOnceOptions
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

复制到剪贴板
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

Asset暂停选项
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

Asset恢复选项
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

资源
export interface Assets {
/**
* Asset Id, unique identifier of the file
*/
assetId: string;
}

AssetStopOptions

Asset停止选项
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

资产体积
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

资产费率
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

资产设置时间
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在上游发生变化时,请重新同步

继续从开始

继续 Getting Started

如果您正在使用 开始使用 来规划原生媒体和界面行为,连接它与 使用 @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-视频播放器 关于 @capgo/capacitor-视频播放器 的实现细节。