@capgo/native-audio 8.1.10 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -243,6 +243,97 @@ The media control buttons automatically handle:
243
243
  - iOS: Uses MPNowPlayingInfoCenter with MPRemoteCommandCenter
244
244
  - Android: Uses MediaSession with NotificationCompat.MediaStyle
245
245
 
246
+ ### Android Background Playback @since 8.2.0
247
+
248
+ By default, Android apps pause audio when the app is backgrounded or the screen is locked. To enable continuous audio playback in the background (for meditation apps, music players, podcast players, etc.), use the `backgroundPlayback` flag.
249
+
250
+ > **⚠️ Important Android Requirements**
251
+ >
252
+ > To use background playback on Android, your app must meet these requirements:
253
+ > 1. Declare the required permissions in `AndroidManifest.xml`
254
+ > 2. Start an Android Foreground Service with a media notification
255
+ > 3. Configure the plugin with `backgroundPlayback: true`
256
+
257
+ **Step 1: Add required permissions to `AndroidManifest.xml`**
258
+
259
+ ```xml
260
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
261
+ <!-- Required for background audio playback -->
262
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
263
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
264
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
265
+
266
+ <application>
267
+ <!-- Your app configuration -->
268
+ </application>
269
+ </manifest>
270
+ ```
271
+
272
+ **Step 2: Configure the plugin with background playback enabled**
273
+
274
+ ```typescript
275
+ import { NativeAudio } from '@capgo/native-audio';
276
+
277
+ // Enable background playback and notification center
278
+ await NativeAudio.configure({
279
+ backgroundPlayback: true, // Prevent automatic pause when backgrounded
280
+ showNotification: true, // Show playback controls in notification
281
+ focus: true // Request audio focus (optional but recommended)
282
+ });
283
+ ```
284
+
285
+ **Step 3: Start a Foreground Service (your responsibility)**
286
+
287
+ The plugin does NOT automatically create or manage the Android Foreground Service. You must create and start your own foreground service using a Capacitor plugin like [`@capacitor/local-notifications`](https://capacitorjs.com/docs/apis/local-notifications) or a custom Android service.
288
+
289
+ Here's a conceptual example:
290
+
291
+ ```typescript
292
+ // 1. Configure the audio plugin
293
+ await NativeAudio.configure({
294
+ backgroundPlayback: true,
295
+ showNotification: true
296
+ });
297
+
298
+ // 2. Start your foreground service (implementation depends on your app)
299
+ // This is typically done with a native Android service or a plugin
300
+ // that provides foreground service capabilities
301
+ await startForegroundService();
302
+
303
+ // 3. Preload and play audio as normal
304
+ await NativeAudio.preload({
305
+ assetId: 'meditation',
306
+ assetPath: 'audio/meditation.mp3',
307
+ notificationMetadata: {
308
+ title: 'Meditation Session',
309
+ artist: 'Your App Name'
310
+ }
311
+ });
312
+
313
+ await NativeAudio.play({ assetId: 'meditation' });
314
+
315
+ // Audio will continue playing when app is backgrounded
316
+ // The foreground service ensures Android allows background playback
317
+ ```
318
+
319
+ **Important timing notes:**
320
+ - The foreground service should be started **before** the app enters the background
321
+ - Start the service immediately after configuring the audio plugin and before playing audio
322
+ - If the foreground service is not running, Android may still kill your audio playback
323
+
324
+ **How it works:**
325
+ - Without `backgroundPlayback: true`: The plugin automatically pauses all audio when the app enters the background
326
+ - With `backgroundPlayback: true`: The plugin skips automatic pause/resume, allowing continuous playback
327
+
328
+ **Important notes:**
329
+ - This flag is **Android-only** (iOS already supports background playback via AVAudioSession)
330
+ - You **must** start an Android Foreground Service separately (plugin does not handle this)
331
+ - Combine with `showNotification: true` to display playback controls
332
+ - Starting Android 14+, foreground services require the `FOREGROUND_SERVICE_MEDIA_PLAYBACK` permission type
333
+
334
+ **Alternative approach:**
335
+ If you need a complete solution including foreground service management, consider using a dedicated media playback plugin or implementing a custom Android service in your app's native code.
336
+
246
337
  ## Play Once (Fire-and-Forget) @since 7.11.0
247
338
 
248
339
  For simple one-shot audio playback (sound effects, notifications, etc.), use `playOnce()` which handles the entire asset lifecycle automatically:
@@ -825,13 +916,14 @@ Use this when you need to ensure compatibility with other audio plugins
825
916
 
826
917
  #### ConfigureOptions
827
918
 
828
- | Prop | Type | Description |
829
- | ---------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
830
- | **`fade`** | <code>boolean</code> | Play the audio with Fade effect, only available for IOS |
831
- | **`focus`** | <code>boolean</code> | focus the audio with Audio Focus |
832
- | **`background`** | <code>boolean</code> | Play the audio in the background |
833
- | **`ignoreSilent`** | <code>boolean</code> | Ignore silent mode, works only on iOS setting this will nuke other audio apps |
834
- | **`showNotification`** | <code>boolean</code> | 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. |
919
+ | Prop | Type | Description | Default | Since |
920
+ | ------------------------ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ----- |
921
+ | **`fade`** | <code>boolean</code> | Play the audio with Fade effect, only available for IOS | | |
922
+ | **`focus`** | <code>boolean</code> | focus the audio with Audio Focus | | |
923
+ | **`background`** | <code>boolean</code> | Play the audio in the background | | |
924
+ | **`ignoreSilent`** | <code>boolean</code> | Ignore silent mode, works only on iOS setting this will nuke other audio apps | | |
925
+ | **`showNotification`** | <code>boolean</code> | 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. | | |
926
+ | **`backgroundPlayback`** | <code>boolean</code> | 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`: - `&lt;uses-permission android:name="android.permission.FOREGROUND_SERVICE" /&gt;` - `&lt;uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /&gt;` - `&lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;` 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 ``` | <code>false</code> | 8.2.0 |
835
927
 
836
928
 
837
929
  #### PreloadOptions
@@ -80,7 +80,7 @@ dependencies {
80
80
 
81
81
  implementation 'androidx.media3:media3-session:1.9.0'
82
82
  implementation 'androidx.media3:media3-transformer:1.9.0'
83
- implementation 'androidx.media3:media3-ui:1.8.0'
83
+ implementation 'androidx.media3:media3-ui:1.9.0'
84
84
  implementation 'androidx.media3:media3-database:1.9.0'
85
85
  implementation 'androidx.media3:media3-common:1.9.0'
86
86
  // Media notification support
@@ -90,6 +90,9 @@ public class NativeAudio extends Plugin implements AudioManager.OnAudioFocusChan
90
90
  // Track playOnce assets for automatic cleanup
91
91
  private Set<String> playOnceAssets = new HashSet<>();
92
92
 
93
+ // Background playback support
94
+ private boolean backgroundPlayback = false;
95
+
93
96
  /**
94
97
  * Initializes plugin runtime state by obtaining the system {@link AudioManager}, preparing the asset map,
95
98
  * and recording the device's original audio mode without requesting audio focus.
@@ -143,6 +146,12 @@ public class NativeAudio extends Plugin implements AudioManager.OnAudioFocusChan
143
146
  protected void handleOnPause() {
144
147
  super.handleOnPause();
145
148
 
149
+ // Skip automatic pause when background playback is enabled
150
+ if (backgroundPlayback) {
151
+ Log.d(TAG, "Background playback enabled - skipping automatic pause");
152
+ return;
153
+ }
154
+
146
155
  try {
147
156
  if (audioAssetList != null) {
148
157
  for (HashMap.Entry<String, AudioAsset> entry : audioAssetList.entrySet()) {
@@ -166,6 +175,12 @@ public class NativeAudio extends Plugin implements AudioManager.OnAudioFocusChan
166
175
  protected void handleOnResume() {
167
176
  super.handleOnResume();
168
177
 
178
+ // Skip automatic resume when background playback is enabled
179
+ if (backgroundPlayback) {
180
+ Log.d(TAG, "Background playback enabled - skipping automatic resume");
181
+ return;
182
+ }
183
+
169
184
  try {
170
185
  if (resumeList != null) {
171
186
  while (!resumeList.isEmpty()) {
@@ -199,6 +214,7 @@ public class NativeAudio extends Plugin implements AudioManager.OnAudioFocusChan
199
214
  boolean background = call.getBoolean("background", false);
200
215
  this.fadeMusic = call.getBoolean("fade", false);
201
216
  this.showNotification = call.getBoolean(SHOW_NOTIFICATION, false);
217
+ this.backgroundPlayback = call.getBoolean("backgroundPlayback", false);
202
218
 
203
219
  try {
204
220
  if (focus) {
package/dist/docs.json CHANGED
@@ -708,6 +708,26 @@
708
708
  "docs": "Show audio playback in the notification center (iOS and Android)\nWhen enabled, displays audio metadata (title, artist, album, artwork) in the system notification\nand Control Center (iOS) or lock screen.\n\n**Important iOS Behavior:**\nEnabling this option changes the audio session category to `.playback` with `.default` mode,\nwhich means your app's audio will **interrupt** other apps' audio (like background music from\nSpotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing\ninfo to appear in Control Center and on the lock screen.\n\n**Trade-offs:**\n- `showNotification: true` → Shows Now Playing controls, but interrupts other audio\n- `showNotification: false` → Audio mixes with other apps, but no Now Playing controls\n\nUse this when your app is the primary audio source (music players, podcast apps, etc.).\nDisable this for secondary audio like sound effects or notification sounds where mixing\nwith background music is preferred.",
709
709
  "complexTypes": [],
710
710
  "type": "boolean | undefined"
711
+ },
712
+ {
713
+ "name": "backgroundPlayback",
714
+ "tags": [
715
+ {
716
+ "text": "false",
717
+ "name": "default"
718
+ },
719
+ {
720
+ "text": "Android",
721
+ "name": "platform"
722
+ },
723
+ {
724
+ "text": "8.2.0",
725
+ "name": "since"
726
+ }
727
+ ],
728
+ "docs": "Enable background audio playback (Android only)\n\nWhen enabled, audio will continue playing when the app is backgrounded or the screen is locked.\nThe plugin will skip the automatic pause/resume logic that normally occurs when the app\nenters the background or returns to the foreground.\n\n**Important Android Requirements:**\nTo use background playback on Android, your app must:\n1. Declare the required permissions in `AndroidManifest.xml`:\n - `<uses-permission android:name=\"android.permission.FOREGROUND_SERVICE\" />`\n - `<uses-permission android:name=\"android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK\" />`\n - `<uses-permission android:name=\"android.permission.WAKE_LOCK\" />`\n2. Start a Foreground Service with a media-style notification before backgrounding\n (the plugin does not automatically create or manage the foreground service)\n3. Use `showNotification: true` to display playback controls in the notification\n\n**Usage Example:**\n```typescript\nawait NativeAudio.configure({\n backgroundPlayback: true,\n showNotification: true\n});\n// Start your foreground service here\n// Then preload and play audio as normal\n```",
729
+ "complexTypes": [],
730
+ "type": "boolean | undefined"
711
731
  }
712
732
  ]
713
733
  },
@@ -87,6 +87,38 @@ export interface ConfigureOptions {
87
87
  * @see https://github.com/Cap-go/capacitor-native-audio/issues/202
88
88
  */
89
89
  showNotification?: boolean;
90
+ /**
91
+ * Enable background audio playback (Android only)
92
+ *
93
+ * When enabled, audio will continue playing when the app is backgrounded or the screen is locked.
94
+ * The plugin will skip the automatic pause/resume logic that normally occurs when the app
95
+ * enters the background or returns to the foreground.
96
+ *
97
+ * **Important Android Requirements:**
98
+ * To use background playback on Android, your app must:
99
+ * 1. Declare the required permissions in `AndroidManifest.xml`:
100
+ * - `<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />`
101
+ * - `<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />`
102
+ * - `<uses-permission android:name="android.permission.WAKE_LOCK" />`
103
+ * 2. Start a Foreground Service with a media-style notification before backgrounding
104
+ * (the plugin does not automatically create or manage the foreground service)
105
+ * 3. Use `showNotification: true` to display playback controls in the notification
106
+ *
107
+ * **Usage Example:**
108
+ * ```typescript
109
+ * await NativeAudio.configure({
110
+ * backgroundPlayback: true,
111
+ * showNotification: true
112
+ * });
113
+ * // Start your foreground service here
114
+ * // Then preload and play audio as normal
115
+ * ```
116
+ *
117
+ * @default false
118
+ * @platform Android
119
+ * @since 8.2.0
120
+ */
121
+ backgroundPlayback?: boolean;
90
122
  }
91
123
  /**
92
124
  * Metadata to display in the notification center, Control Center (iOS), and lock screen
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\nexport interface CompletedEvent {\n /**\n * Emit when a play completes\n *\n * @since 5.0.0\n */\n assetId: string;\n}\nexport type CompletedListener = (state: CompletedEvent) => void;\nexport interface Assets {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n}\nexport interface AssetVolume {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Volume of the audio, between 0.1 and 1.0\n */\n volume: number;\n}\n\nexport interface AssetRate {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Rate of the audio, between 0.1 and 1.0\n */\n rate: number;\n}\n\nexport interface AssetPlayOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Time to start playing the audio, in milliseconds\n */\n time?: number;\n /**\n * Delay to start playing the audio, in milliseconds\n */\n delay?: number;\n}\n\nexport interface ConfigureOptions {\n /**\n * Play the audio with Fade effect, only available for IOS\n */\n fade?: boolean;\n /**\n * focus the audio with Audio Focus\n */\n focus?: boolean;\n /**\n * Play the audio in the background\n */\n background?: boolean;\n /**\n * Ignore silent mode, works only on iOS setting this will nuke other audio apps\n */\n ignoreSilent?: boolean;\n /**\n * Show audio playback in the notification center (iOS and Android)\n * When enabled, displays audio metadata (title, artist, album, artwork) in the system notification\n * and Control Center (iOS) or lock screen.\n *\n * **Important iOS Behavior:**\n * Enabling this option changes the audio session category to `.playback` with `.default` mode,\n * which means your app's audio will **interrupt** other apps' audio (like background music from\n * Spotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing\n * info to appear in Control Center and on the lock screen.\n *\n * **Trade-offs:**\n * - `showNotification: true` → Shows Now Playing controls, but interrupts other audio\n * - `showNotification: false` → Audio mixes with other apps, but no Now Playing controls\n *\n * Use this when your app is the primary audio source (music players, podcast apps, etc.).\n * Disable this for secondary audio like sound effects or notification sounds where mixing\n * with background music is preferred.\n *\n * @see https://github.com/Cap-go/capacitor-native-audio/issues/202\n */\n showNotification?: boolean;\n}\n\n/**\n * Metadata to display in the notification center, Control Center (iOS), and lock screen\n * when `showNotification` is enabled in `configure()`.\n *\n * Note: This metadata will only be displayed if `showNotification: true` is set in the\n * `configure()` method. See {@link ConfigureOptions.showNotification} for important\n * behavior details about audio mixing on iOS.\n */\nexport interface NotificationMetadata {\n /**\n * The title to display in the notification center\n */\n title?: string;\n /**\n * The artist name to display in the notification center\n */\n artist?: string;\n /**\n * The album name to display in the notification center\n */\n album?: string;\n /**\n * URL or local path to the artwork/album art image\n */\n artworkUrl?: string;\n}\n\nexport interface PlayOnceOptions {\n /**\n * Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://)\n * Supported formats:\n * - MP3, WAV (all platforms)\n * - M3U8/HLS streams (iOS and Android)\n */\n assetPath: string;\n /**\n * Volume of the audio, between 0.1 and 1.0\n * @default 1.0\n */\n volume?: number;\n /**\n * Is the audio file a URL, pass true if assetPath is a `file://` url\n * or a streaming URL (m3u8)\n * @default false\n */\n isUrl?: boolean;\n /**\n * Automatically start playback after loading\n * @default true\n */\n autoPlay?: boolean;\n /**\n * Delete the audio file from disk after playback completes\n * Only works for local files (file:// URLs), ignored for remote URLs\n * @default false\n * @since 7.11.0\n */\n deleteAfterPlay?: boolean;\n /**\n * Metadata to display in the notification center when audio is playing.\n * Only used when `showNotification: true` is set in `configure()`.\n *\n * See {@link ConfigureOptions.showNotification} for important details about\n * how this affects audio mixing behavior on iOS.\n *\n * @see NotificationMetadata\n * @since 7.10.0\n */\n notificationMetadata?: NotificationMetadata;\n /**\n * Custom HTTP headers to include when fetching remote audio files.\n * Only used when isUrl is true and assetPath is a remote URL (http/https).\n * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }\n *\n * @since 7.10.0\n */\n headers?: Record<string, string>;\n}\n\nexport interface PlayOnceResult {\n /**\n * The internally generated asset ID for this playback\n * Can be used to control playback (pause, stop, etc.) before completion\n */\n assetId: string;\n}\n\nexport interface PreloadOptions {\n /**\n * Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://)\n * Supported formats:\n * - MP3, WAV (all platforms)\n * - M3U8/HLS streams (iOS and Android)\n */\n assetPath: string;\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Volume of the audio, between 0.1 and 1.0\n */\n volume?: number;\n /**\n * Audio channel number, default is 1\n */\n audioChannelNum?: number;\n /**\n * Is the audio file a URL, pass true if assetPath is a `file://` url\n * or a streaming URL (m3u8)\n */\n isUrl?: boolean;\n /**\n * Metadata to display in the notification center when audio is playing.\n * Only used when `showNotification: true` is set in `configure()`.\n *\n * See {@link ConfigureOptions.showNotification} for important details about\n * how this affects audio mixing behavior on iOS.\n *\n * @see NotificationMetadata\n */\n notificationMetadata?: NotificationMetadata;\n /**\n * Custom HTTP headers to include when fetching remote audio files.\n * Only used when isUrl is true and assetPath is a remote URL (http/https).\n * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }\n *\n * @since 7.10.0\n */\n headers?: Record<string, string>;\n}\n\nexport interface CurrentTimeEvent {\n /**\n * Current time of the audio in seconds\n * @since 6.5.0\n */\n currentTime: number;\n /**\n * Asset Id of the audio\n * @since 6.5.0\n */\n assetId: string;\n}\nexport type CurrentTimeListener = (state: CurrentTimeEvent) => void;\n\nexport interface NativeAudio {\n /**\n * Configure the audio player\n * @since 5.0.0\n * @param option {@link ConfigureOptions}\n * @returns\n */\n configure(options: ConfigureOptions): Promise<void>;\n /**\n * Load an audio file\n * @since 5.0.0\n * @param option {@link PreloadOptions}\n * @returns\n */\n preload(options: PreloadOptions): Promise<void>;\n /**\n * Play an audio file once with automatic cleanup\n *\n * Method designed for simple, single-shot audio playback,\n * such as notification sounds, UI feedback, or other short audio clips\n * that don't require manual state management.\n *\n * **Key Features:**\n * - **Fire-and-forget**: No need to manually preload, play, stop, or unload\n * - **Auto-cleanup**: Asset is automatically unloaded after playback completes\n * - **Optional file deletion**: Can delete local files after playback (useful for temp files)\n * - **Returns assetId**: Can still control playback if needed (pause, stop, etc.)\n *\n * **Use Cases:**\n * - Notification sounds\n * - UI sound effects (button clicks, alerts)\n * - Short audio clips that play once\n * - Temporary audio files that should be cleaned up\n *\n * **Comparison with regular play():**\n * - `play()`: Requires manual preload, play, and unload steps\n * - `playOnce()`: Handles everything automatically with a single call\n *\n * @example\n * ```typescript\n * // Simple one-shot playback\n * await NativeAudio.playOnce({ assetPath: 'audio/notification.mp3' });\n *\n * // Play and delete the file after completion\n * await NativeAudio.playOnce({\n * assetPath: 'file:///path/to/temp/audio.mp3',\n * isUrl: true,\n * deleteAfterPlay: true\n * });\n *\n * // Get the assetId to control playback\n * const { assetId } = await NativeAudio.playOnce({\n * assetPath: 'audio/long-track.mp3',\n * autoPlay: true\n * });\n * // Later, you can stop it manually if needed\n * await NativeAudio.stop({ assetId });\n * ```\n *\n * @since 7.11.0\n * @param options {@link PlayOnceOptions}\n * @returns {Promise<PlayOnceResult>} Object containing the generated assetId\n */\n playOnce(options: PlayOnceOptions): Promise<PlayOnceResult>;\n /**\n * Check if an audio file is preloaded\n *\n * @since 6.1.0\n * @param option {@link Assets}\n * @returns {Promise<boolean>}\n */\n isPreloaded(options: PreloadOptions): Promise<{ found: boolean }>;\n /**\n * Play an audio file\n * @since 5.0.0\n * @param option {@link PlayOptions}\n * @returns\n */\n play(options: { assetId: string; time?: number; delay?: number }): Promise<void>;\n /**\n * Pause an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n pause(options: Assets): Promise<void>;\n /**\n * Resume an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n resume(options: Assets): Promise<void>;\n /**\n * Stop an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n loop(options: Assets): Promise<void>;\n /**\n * Stop an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n stop(options: Assets): Promise<void>;\n /**\n * Unload an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n unload(options: Assets): Promise<void>;\n /**\n * Set the volume of an audio file\n * @since 5.0.0\n * @param option {@link AssetVolume}\n * @returns {Promise<void>}\n */\n setVolume(options: { assetId: string; volume: number }): Promise<void>;\n /**\n * Set the rate of an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<void>}\n */\n setRate(options: { assetId: string; rate: number }): Promise<void>;\n /**\n * Set the current time of an audio file\n * @since 6.5.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<void>}\n */\n setCurrentTime(options: { assetId: string; time: number }): Promise<void>;\n /**\n * Get the current time of an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<{ currentTime: number }>}\n */\n getCurrentTime(options: { assetId: string }): Promise<{ currentTime: number }>;\n /**\n * Get the duration of an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<{ duration: number }>}\n */\n getDuration(options: Assets): Promise<{ duration: number }>;\n /**\n * Check if an audio file is playing\n *\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<boolean>}\n */\n isPlaying(options: Assets): Promise<{ isPlaying: boolean }>;\n /**\n * Listen for complete event\n *\n * @since 5.0.0\n * return {@link CompletedEvent}\n */\n addListener(eventName: 'complete', listenerFunc: CompletedListener): Promise<PluginListenerHandle>;\n /**\n * Listen for current time updates\n * Emits every 100ms while audio is playing\n *\n * @since 6.5.0\n * return {@link CurrentTimeEvent}\n */\n addListener(eventName: 'currentTime', listenerFunc: CurrentTimeListener): Promise<PluginListenerHandle>;\n /**\n * Clear the audio cache for remote audio files\n * @since 6.5.0\n * @returns {Promise<void>}\n */\n clearCache(): Promise<void>;\n\n /**\n * Get the native Capacitor plugin version\n *\n * @returns {Promise<{ id: string }>} an Promise with version for this device\n * @throws An error if the something went wrong\n */\n getPluginVersion(): Promise<{ version: string }>;\n\n /**\n * Deinitialize the plugin and restore original audio session settings\n * This method stops all playing audio and reverts any audio session changes made by the plugin\n * Use this when you need to ensure compatibility with other audio plugins\n *\n * @since 7.7.0\n * @returns {Promise<void>}\n */\n deinitPlugin(): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type { PluginListenerHandle } from '@capacitor/core';\n\nexport interface CompletedEvent {\n /**\n * Emit when a play completes\n *\n * @since 5.0.0\n */\n assetId: string;\n}\nexport type CompletedListener = (state: CompletedEvent) => void;\nexport interface Assets {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n}\nexport interface AssetVolume {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Volume of the audio, between 0.1 and 1.0\n */\n volume: number;\n}\n\nexport interface AssetRate {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Rate of the audio, between 0.1 and 1.0\n */\n rate: number;\n}\n\nexport interface AssetPlayOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Time to start playing the audio, in milliseconds\n */\n time?: number;\n /**\n * Delay to start playing the audio, in milliseconds\n */\n delay?: number;\n}\n\nexport interface ConfigureOptions {\n /**\n * Play the audio with Fade effect, only available for IOS\n */\n fade?: boolean;\n /**\n * focus the audio with Audio Focus\n */\n focus?: boolean;\n /**\n * Play the audio in the background\n */\n background?: boolean;\n /**\n * Ignore silent mode, works only on iOS setting this will nuke other audio apps\n */\n ignoreSilent?: boolean;\n /**\n * Show audio playback in the notification center (iOS and Android)\n * When enabled, displays audio metadata (title, artist, album, artwork) in the system notification\n * and Control Center (iOS) or lock screen.\n *\n * **Important iOS Behavior:**\n * Enabling this option changes the audio session category to `.playback` with `.default` mode,\n * which means your app's audio will **interrupt** other apps' audio (like background music from\n * Spotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing\n * info to appear in Control Center and on the lock screen.\n *\n * **Trade-offs:**\n * - `showNotification: true` → Shows Now Playing controls, but interrupts other audio\n * - `showNotification: false` → Audio mixes with other apps, but no Now Playing controls\n *\n * Use this when your app is the primary audio source (music players, podcast apps, etc.).\n * Disable this for secondary audio like sound effects or notification sounds where mixing\n * with background music is preferred.\n *\n * @see https://github.com/Cap-go/capacitor-native-audio/issues/202\n */\n showNotification?: boolean;\n /**\n * Enable background audio playback (Android only)\n *\n * When enabled, audio will continue playing when the app is backgrounded or the screen is locked.\n * The plugin will skip the automatic pause/resume logic that normally occurs when the app\n * enters the background or returns to the foreground.\n *\n * **Important Android Requirements:**\n * To use background playback on Android, your app must:\n * 1. Declare the required permissions in `AndroidManifest.xml`:\n * - `<uses-permission android:name=\"android.permission.FOREGROUND_SERVICE\" />`\n * - `<uses-permission android:name=\"android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK\" />`\n * - `<uses-permission android:name=\"android.permission.WAKE_LOCK\" />`\n * 2. Start a Foreground Service with a media-style notification before backgrounding\n * (the plugin does not automatically create or manage the foreground service)\n * 3. Use `showNotification: true` to display playback controls in the notification\n *\n * **Usage Example:**\n * ```typescript\n * await NativeAudio.configure({\n * backgroundPlayback: true,\n * showNotification: true\n * });\n * // Start your foreground service here\n * // Then preload and play audio as normal\n * ```\n *\n * @default false\n * @platform Android\n * @since 8.2.0\n */\n backgroundPlayback?: boolean;\n}\n\n/**\n * Metadata to display in the notification center, Control Center (iOS), and lock screen\n * when `showNotification` is enabled in `configure()`.\n *\n * Note: This metadata will only be displayed if `showNotification: true` is set in the\n * `configure()` method. See {@link ConfigureOptions.showNotification} for important\n * behavior details about audio mixing on iOS.\n */\nexport interface NotificationMetadata {\n /**\n * The title to display in the notification center\n */\n title?: string;\n /**\n * The artist name to display in the notification center\n */\n artist?: string;\n /**\n * The album name to display in the notification center\n */\n album?: string;\n /**\n * URL or local path to the artwork/album art image\n */\n artworkUrl?: string;\n}\n\nexport interface PlayOnceOptions {\n /**\n * Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://)\n * Supported formats:\n * - MP3, WAV (all platforms)\n * - M3U8/HLS streams (iOS and Android)\n */\n assetPath: string;\n /**\n * Volume of the audio, between 0.1 and 1.0\n * @default 1.0\n */\n volume?: number;\n /**\n * Is the audio file a URL, pass true if assetPath is a `file://` url\n * or a streaming URL (m3u8)\n * @default false\n */\n isUrl?: boolean;\n /**\n * Automatically start playback after loading\n * @default true\n */\n autoPlay?: boolean;\n /**\n * Delete the audio file from disk after playback completes\n * Only works for local files (file:// URLs), ignored for remote URLs\n * @default false\n * @since 7.11.0\n */\n deleteAfterPlay?: boolean;\n /**\n * Metadata to display in the notification center when audio is playing.\n * Only used when `showNotification: true` is set in `configure()`.\n *\n * See {@link ConfigureOptions.showNotification} for important details about\n * how this affects audio mixing behavior on iOS.\n *\n * @see NotificationMetadata\n * @since 7.10.0\n */\n notificationMetadata?: NotificationMetadata;\n /**\n * Custom HTTP headers to include when fetching remote audio files.\n * Only used when isUrl is true and assetPath is a remote URL (http/https).\n * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }\n *\n * @since 7.10.0\n */\n headers?: Record<string, string>;\n}\n\nexport interface PlayOnceResult {\n /**\n * The internally generated asset ID for this playback\n * Can be used to control playback (pause, stop, etc.) before completion\n */\n assetId: string;\n}\n\nexport interface PreloadOptions {\n /**\n * Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://)\n * Supported formats:\n * - MP3, WAV (all platforms)\n * - M3U8/HLS streams (iOS and Android)\n */\n assetPath: string;\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Volume of the audio, between 0.1 and 1.0\n */\n volume?: number;\n /**\n * Audio channel number, default is 1\n */\n audioChannelNum?: number;\n /**\n * Is the audio file a URL, pass true if assetPath is a `file://` url\n * or a streaming URL (m3u8)\n */\n isUrl?: boolean;\n /**\n * Metadata to display in the notification center when audio is playing.\n * Only used when `showNotification: true` is set in `configure()`.\n *\n * See {@link ConfigureOptions.showNotification} for important details about\n * how this affects audio mixing behavior on iOS.\n *\n * @see NotificationMetadata\n */\n notificationMetadata?: NotificationMetadata;\n /**\n * Custom HTTP headers to include when fetching remote audio files.\n * Only used when isUrl is true and assetPath is a remote URL (http/https).\n * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }\n *\n * @since 7.10.0\n */\n headers?: Record<string, string>;\n}\n\nexport interface CurrentTimeEvent {\n /**\n * Current time of the audio in seconds\n * @since 6.5.0\n */\n currentTime: number;\n /**\n * Asset Id of the audio\n * @since 6.5.0\n */\n assetId: string;\n}\nexport type CurrentTimeListener = (state: CurrentTimeEvent) => void;\n\nexport interface NativeAudio {\n /**\n * Configure the audio player\n * @since 5.0.0\n * @param option {@link ConfigureOptions}\n * @returns\n */\n configure(options: ConfigureOptions): Promise<void>;\n /**\n * Load an audio file\n * @since 5.0.0\n * @param option {@link PreloadOptions}\n * @returns\n */\n preload(options: PreloadOptions): Promise<void>;\n /**\n * Play an audio file once with automatic cleanup\n *\n * Method designed for simple, single-shot audio playback,\n * such as notification sounds, UI feedback, or other short audio clips\n * that don't require manual state management.\n *\n * **Key Features:**\n * - **Fire-and-forget**: No need to manually preload, play, stop, or unload\n * - **Auto-cleanup**: Asset is automatically unloaded after playback completes\n * - **Optional file deletion**: Can delete local files after playback (useful for temp files)\n * - **Returns assetId**: Can still control playback if needed (pause, stop, etc.)\n *\n * **Use Cases:**\n * - Notification sounds\n * - UI sound effects (button clicks, alerts)\n * - Short audio clips that play once\n * - Temporary audio files that should be cleaned up\n *\n * **Comparison with regular play():**\n * - `play()`: Requires manual preload, play, and unload steps\n * - `playOnce()`: Handles everything automatically with a single call\n *\n * @example\n * ```typescript\n * // Simple one-shot playback\n * await NativeAudio.playOnce({ assetPath: 'audio/notification.mp3' });\n *\n * // Play and delete the file after completion\n * await NativeAudio.playOnce({\n * assetPath: 'file:///path/to/temp/audio.mp3',\n * isUrl: true,\n * deleteAfterPlay: true\n * });\n *\n * // Get the assetId to control playback\n * const { assetId } = await NativeAudio.playOnce({\n * assetPath: 'audio/long-track.mp3',\n * autoPlay: true\n * });\n * // Later, you can stop it manually if needed\n * await NativeAudio.stop({ assetId });\n * ```\n *\n * @since 7.11.0\n * @param options {@link PlayOnceOptions}\n * @returns {Promise<PlayOnceResult>} Object containing the generated assetId\n */\n playOnce(options: PlayOnceOptions): Promise<PlayOnceResult>;\n /**\n * Check if an audio file is preloaded\n *\n * @since 6.1.0\n * @param option {@link Assets}\n * @returns {Promise<boolean>}\n */\n isPreloaded(options: PreloadOptions): Promise<{ found: boolean }>;\n /**\n * Play an audio file\n * @since 5.0.0\n * @param option {@link PlayOptions}\n * @returns\n */\n play(options: { assetId: string; time?: number; delay?: number }): Promise<void>;\n /**\n * Pause an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n pause(options: Assets): Promise<void>;\n /**\n * Resume an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n resume(options: Assets): Promise<void>;\n /**\n * Stop an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n loop(options: Assets): Promise<void>;\n /**\n * Stop an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n stop(options: Assets): Promise<void>;\n /**\n * Unload an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns\n */\n unload(options: Assets): Promise<void>;\n /**\n * Set the volume of an audio file\n * @since 5.0.0\n * @param option {@link AssetVolume}\n * @returns {Promise<void>}\n */\n setVolume(options: { assetId: string; volume: number }): Promise<void>;\n /**\n * Set the rate of an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<void>}\n */\n setRate(options: { assetId: string; rate: number }): Promise<void>;\n /**\n * Set the current time of an audio file\n * @since 6.5.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<void>}\n */\n setCurrentTime(options: { assetId: string; time: number }): Promise<void>;\n /**\n * Get the current time of an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<{ currentTime: number }>}\n */\n getCurrentTime(options: { assetId: string }): Promise<{ currentTime: number }>;\n /**\n * Get the duration of an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<{ duration: number }>}\n */\n getDuration(options: Assets): Promise<{ duration: number }>;\n /**\n * Check if an audio file is playing\n *\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns {Promise<boolean>}\n */\n isPlaying(options: Assets): Promise<{ isPlaying: boolean }>;\n /**\n * Listen for complete event\n *\n * @since 5.0.0\n * return {@link CompletedEvent}\n */\n addListener(eventName: 'complete', listenerFunc: CompletedListener): Promise<PluginListenerHandle>;\n /**\n * Listen for current time updates\n * Emits every 100ms while audio is playing\n *\n * @since 6.5.0\n * return {@link CurrentTimeEvent}\n */\n addListener(eventName: 'currentTime', listenerFunc: CurrentTimeListener): Promise<PluginListenerHandle>;\n /**\n * Clear the audio cache for remote audio files\n * @since 6.5.0\n * @returns {Promise<void>}\n */\n clearCache(): Promise<void>;\n\n /**\n * Get the native Capacitor plugin version\n *\n * @returns {Promise<{ id: string }>} an Promise with version for this device\n * @throws An error if the something went wrong\n */\n getPluginVersion(): Promise<{ version: string }>;\n\n /**\n * Deinitialize the plugin and restore original audio session settings\n * This method stops all playing audio and reverts any audio session changes made by the plugin\n * Use this when you need to ensure compatibility with other audio plugins\n *\n * @since 7.7.0\n * @returns {Promise<void>}\n */\n deinitPlugin(): Promise<void>;\n}\n"]}
@@ -13,7 +13,7 @@ enum MyError: Error {
13
13
  // swiftlint:disable type_body_length file_length
14
14
  @objc(NativeAudio)
15
15
  public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
16
- private let pluginVersion: String = "8.1.10"
16
+ private let pluginVersion: String = "8.2.0"
17
17
  public let identifier = "NativeAudio"
18
18
  public let jsName = "NativeAudio"
19
19
  public let pluginMethods: [CAPPluginMethod] = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/native-audio",
3
- "version": "8.1.10",
3
+ "version": "8.2.0",
4
4
  "description": "A native plugin for native audio engine",
5
5
  "license": "MPL-2.0",
6
6
  "main": "dist/plugin.cjs.js",