@capgo/native-audio 8.4.0 → 8.4.1

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/dist/docs.json CHANGED
@@ -613,6 +613,35 @@
613
613
  ],
614
614
  "slug": "addlistenercurrenttime-"
615
615
  },
616
+ {
617
+ "name": "addListener",
618
+ "signature": "(eventName: 'playbackState', listenerFunc: PlaybackStateListener) => Promise<PluginListenerHandle>",
619
+ "parameters": [
620
+ {
621
+ "name": "eventName",
622
+ "docs": "",
623
+ "type": "'playbackState'"
624
+ },
625
+ {
626
+ "name": "listenerFunc",
627
+ "docs": "",
628
+ "type": "PlaybackStateListener"
629
+ }
630
+ ],
631
+ "returns": "Promise<PluginListenerHandle>",
632
+ "tags": [
633
+ {
634
+ "name": "since",
635
+ "text": "8.3.15\nreturn {@link PlaybackStateEvent}"
636
+ }
637
+ ],
638
+ "docs": "Listen for playback state changes, including notification and lock-screen transport controls.\nEmitted by Android and iOS. The current Web implementation does not emit this event.",
639
+ "complexTypes": [
640
+ "PluginListenerHandle",
641
+ "PlaybackStateListener"
642
+ ],
643
+ "slug": "addlistenerplaybackstate-"
644
+ },
616
645
  {
617
646
  "name": "clearCache",
618
647
  "signature": "() => Promise<void>",
@@ -1307,6 +1336,59 @@
1307
1336
  "type": "string"
1308
1337
  }
1309
1338
  ]
1339
+ },
1340
+ {
1341
+ "name": "PlaybackStateEvent",
1342
+ "slug": "playbackstateevent",
1343
+ "docs": "",
1344
+ "tags": [],
1345
+ "methods": [],
1346
+ "properties": [
1347
+ {
1348
+ "name": "assetId",
1349
+ "tags": [],
1350
+ "docs": "Asset Id of the audio",
1351
+ "complexTypes": [],
1352
+ "type": "string"
1353
+ },
1354
+ {
1355
+ "name": "state",
1356
+ "tags": [],
1357
+ "docs": "Resolved playback state after a local or remote transport action.",
1358
+ "complexTypes": [
1359
+ "PlaybackStateValue"
1360
+ ],
1361
+ "type": "PlaybackStateValue"
1362
+ },
1363
+ {
1364
+ "name": "reason",
1365
+ "tags": [],
1366
+ "docs": "Reason for the state change, for example `play`, `pause`, `remotePlay`, or `complete`.",
1367
+ "complexTypes": [],
1368
+ "type": "string"
1369
+ },
1370
+ {
1371
+ "name": "isPlaying",
1372
+ "tags": [],
1373
+ "docs": "Whether the asset is currently playing.",
1374
+ "complexTypes": [],
1375
+ "type": "boolean"
1376
+ },
1377
+ {
1378
+ "name": "currentTime",
1379
+ "tags": [],
1380
+ "docs": "Current playback position in seconds when available.",
1381
+ "complexTypes": [],
1382
+ "type": "number | undefined"
1383
+ },
1384
+ {
1385
+ "name": "duration",
1386
+ "tags": [],
1387
+ "docs": "Total playback duration in seconds when available.",
1388
+ "complexTypes": [],
1389
+ "type": "number | undefined"
1390
+ }
1391
+ ]
1310
1392
  }
1311
1393
  ],
1312
1394
  "enums": [],
@@ -1350,6 +1432,38 @@
1350
1432
  ]
1351
1433
  }
1352
1434
  ]
1435
+ },
1436
+ {
1437
+ "name": "PlaybackStateListener",
1438
+ "slug": "playbackstatelistener",
1439
+ "docs": "",
1440
+ "types": [
1441
+ {
1442
+ "text": "(state: PlaybackStateEvent): void",
1443
+ "complexTypes": [
1444
+ "PlaybackStateEvent"
1445
+ ]
1446
+ }
1447
+ ]
1448
+ },
1449
+ {
1450
+ "name": "PlaybackStateValue",
1451
+ "slug": "playbackstatevalue",
1452
+ "docs": "",
1453
+ "types": [
1454
+ {
1455
+ "text": "'playing'",
1456
+ "complexTypes": []
1457
+ },
1458
+ {
1459
+ "text": "'paused'",
1460
+ "complexTypes": []
1461
+ },
1462
+ {
1463
+ "text": "'stopped'",
1464
+ "complexTypes": []
1465
+ }
1466
+ ]
1353
1467
  }
1354
1468
  ],
1355
1469
  "pluginConfigs": []
@@ -346,6 +346,34 @@ export interface CurrentTimeEvent {
346
346
  assetId: string;
347
347
  }
348
348
  export type CurrentTimeListener = (state: CurrentTimeEvent) => void;
349
+ export type PlaybackStateValue = 'playing' | 'paused' | 'stopped';
350
+ export interface PlaybackStateEvent {
351
+ /**
352
+ * Asset Id of the audio
353
+ */
354
+ assetId: string;
355
+ /**
356
+ * Resolved playback state after a local or remote transport action.
357
+ */
358
+ state: PlaybackStateValue;
359
+ /**
360
+ * Reason for the state change, for example `play`, `pause`, `remotePlay`, or `complete`.
361
+ */
362
+ reason: string;
363
+ /**
364
+ * Whether the asset is currently playing.
365
+ */
366
+ isPlaying: boolean;
367
+ /**
368
+ * Current playback position in seconds when available.
369
+ */
370
+ currentTime?: number;
371
+ /**
372
+ * Total playback duration in seconds when available.
373
+ */
374
+ duration?: number;
375
+ }
376
+ export type PlaybackStateListener = (state: PlaybackStateEvent) => void;
349
377
  export interface NativeAudio {
350
378
  /**
351
379
  * Configure the audio player
@@ -526,6 +554,14 @@ export interface NativeAudio {
526
554
  * return {@link CurrentTimeEvent}
527
555
  */
528
556
  addListener(eventName: 'currentTime', listenerFunc: CurrentTimeListener): Promise<PluginListenerHandle>;
557
+ /**
558
+ * Listen for playback state changes, including notification and lock-screen transport controls.
559
+ * Emitted by Android and iOS. The current Web implementation does not emit this event.
560
+ *
561
+ * @since 8.3.15
562
+ * return {@link PlaybackStateEvent}
563
+ */
564
+ addListener(eventName: 'playbackState', listenerFunc: PlaybackStateListener): Promise<PluginListenerHandle>;
529
565
  /**
530
566
  * Clear the audio cache for remote audio files
531
567
  * @since 6.5.0
@@ -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}\n\nexport type CompletedListener = (state: CompletedEvent) => void;\n\nexport interface Assets {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n}\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 * Time over which to fade to the target volume, in seconds. Default is 0s (immediate).\n */\n duration?: 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 AssetSetTime {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Time to set the audio, in seconds\n */\n time: 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 seconds\n */\n time?: number;\n /**\n * Delay to start playing the audio, in seconds\n */\n delay?: number;\n\n /**\n * Volume of the audio, between 0.1 and 1.0\n */\n volume?: number;\n\n /**\n * Whether to fade in the audio\n */\n fadeIn?: boolean;\n\n /**\n * Whether to fade out the audio\n */\n fadeOut?: boolean;\n\n /**\n * Fade in duration in seconds.\n * Only used if fadeIn is true.\n * Default is 1s.\n */\n fadeInDuration?: number;\n\n /**\n * Fade out duration in seconds.\n * Only used if fadeOut is true.\n * Default is 1s.\n */\n fadeOutDuration?: number;\n\n /**\n * Time in seconds from the start of the audio to start fading out.\n * Only used if fadeOut is true.\n * Default is fadeOutDuration before end of audio.\n */\n fadeOutStartTime?: number;\n}\n\nexport interface AssetStopOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n\n /**\n * Whether to fade out the audio before stopping\n */\n fadeOut?: boolean;\n\n /**\n * Fade out duration in seconds.\n * Default is 1s.\n */\n fadeOutDuration?: number;\n}\n\nexport interface AssetPauseOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n\n /**\n * Whether to fade out the audio before pausing\n */\n fadeOut?: boolean;\n\n /**\n * Fade out duration in seconds.\n * Default is 1s.\n */\n fadeOutDuration?: number;\n}\n\nexport interface AssetResumeOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n\n /**\n * Whether to fade in the audio during resume\n */\n fadeIn?: boolean;\n\n /**\n * Fade in duration in seconds.\n * Default is 1s.\n */\n fadeInDuration?: number;\n}\n\nexport interface ConfigureOptions {\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}\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 /**\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 /**\n * Play an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns\n */\n play(options: AssetPlayOptions): Promise<void>;\n\n /**\n * Pause an audio file\n * @since 5.0.0\n * @param option {@link AssetPauseOptions}\n * @returns\n */\n pause(options: AssetPauseOptions): Promise<void>;\n\n /**\n * Resume an audio file\n * @since 5.0.0\n * @param option {@link AssetResumeOptions}\n * @returns\n */\n resume(options: AssetResumeOptions): Promise<void>;\n\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 /**\n * Stop an audio file\n * @since 5.0.0\n * @param option {@link AssetStopOptions}\n * @returns\n */\n stop(options: AssetStopOptions): Promise<void>;\n\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 /**\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: AssetVolume): Promise<void>;\n\n /**\n * Set the rate of an audio file\n * @since 5.0.0\n * @param option {@link AssetRate}\n * @returns {Promise<void>}\n */\n setRate(options: AssetRate): Promise<void>;\n\n /**\n * Set the current time of an audio file\n * @since 6.5.0\n * @param option {@link AssetSetTime}\n * @returns {Promise<void>}\n */\n setCurrentTime(options: AssetSetTime): Promise<void>;\n\n /**\n * Get the current time of an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns {Promise<{ currentTime: number }>}\n */\n getCurrentTime(options: Assets): Promise<{ currentTime: number }>;\n\n /**\n * Get the duration of an audio file in seconds\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns {Promise<{ duration: number }>}\n */\n getDuration(options: Assets): Promise<{ duration: number }>;\n\n /**\n * Check if an audio file is playing\n *\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns {Promise<boolean>}\n */\n isPlaying(options: Assets): Promise<{ isPlaying: boolean }>;\n\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 /**\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 * Set debug mode logging\n * @since 6.5.0\n * @param options - Options to enable or disable debug mode\n */\n setDebugMode(options: { enabled: boolean }): 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}\n\nexport type CompletedListener = (state: CompletedEvent) => void;\n\nexport interface Assets {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n}\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 * Time over which to fade to the target volume, in seconds. Default is 0s (immediate).\n */\n duration?: 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 AssetSetTime {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n /**\n * Time to set the audio, in seconds\n */\n time: 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 seconds\n */\n time?: number;\n /**\n * Delay to start playing the audio, in seconds\n */\n delay?: number;\n\n /**\n * Volume of the audio, between 0.1 and 1.0\n */\n volume?: number;\n\n /**\n * Whether to fade in the audio\n */\n fadeIn?: boolean;\n\n /**\n * Whether to fade out the audio\n */\n fadeOut?: boolean;\n\n /**\n * Fade in duration in seconds.\n * Only used if fadeIn is true.\n * Default is 1s.\n */\n fadeInDuration?: number;\n\n /**\n * Fade out duration in seconds.\n * Only used if fadeOut is true.\n * Default is 1s.\n */\n fadeOutDuration?: number;\n\n /**\n * Time in seconds from the start of the audio to start fading out.\n * Only used if fadeOut is true.\n * Default is fadeOutDuration before end of audio.\n */\n fadeOutStartTime?: number;\n}\n\nexport interface AssetStopOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n\n /**\n * Whether to fade out the audio before stopping\n */\n fadeOut?: boolean;\n\n /**\n * Fade out duration in seconds.\n * Default is 1s.\n */\n fadeOutDuration?: number;\n}\n\nexport interface AssetPauseOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n\n /**\n * Whether to fade out the audio before pausing\n */\n fadeOut?: boolean;\n\n /**\n * Fade out duration in seconds.\n * Default is 1s.\n */\n fadeOutDuration?: number;\n}\n\nexport interface AssetResumeOptions {\n /**\n * Asset Id, unique identifier of the file\n */\n assetId: string;\n\n /**\n * Whether to fade in the audio during resume\n */\n fadeIn?: boolean;\n\n /**\n * Fade in duration in seconds.\n * Default is 1s.\n */\n fadeInDuration?: number;\n}\n\nexport interface ConfigureOptions {\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}\n\nexport type CurrentTimeListener = (state: CurrentTimeEvent) => void;\n\nexport type PlaybackStateValue = 'playing' | 'paused' | 'stopped';\n\nexport interface PlaybackStateEvent {\n /**\n * Asset Id of the audio\n */\n assetId: string;\n /**\n * Resolved playback state after a local or remote transport action.\n */\n state: PlaybackStateValue;\n /**\n * Reason for the state change, for example `play`, `pause`, `remotePlay`, or `complete`.\n */\n reason: string;\n /**\n * Whether the asset is currently playing.\n */\n isPlaying: boolean;\n /**\n * Current playback position in seconds when available.\n */\n currentTime?: number;\n /**\n * Total playback duration in seconds when available.\n */\n duration?: number;\n}\n\nexport type PlaybackStateListener = (state: PlaybackStateEvent) => 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 /**\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 /**\n * Play an audio file\n * @since 5.0.0\n * @param option {@link AssetPlayOptions}\n * @returns\n */\n play(options: AssetPlayOptions): Promise<void>;\n\n /**\n * Pause an audio file\n * @since 5.0.0\n * @param option {@link AssetPauseOptions}\n * @returns\n */\n pause(options: AssetPauseOptions): Promise<void>;\n\n /**\n * Resume an audio file\n * @since 5.0.0\n * @param option {@link AssetResumeOptions}\n * @returns\n */\n resume(options: AssetResumeOptions): Promise<void>;\n\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 /**\n * Stop an audio file\n * @since 5.0.0\n * @param option {@link AssetStopOptions}\n * @returns\n */\n stop(options: AssetStopOptions): Promise<void>;\n\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 /**\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: AssetVolume): Promise<void>;\n\n /**\n * Set the rate of an audio file\n * @since 5.0.0\n * @param option {@link AssetRate}\n * @returns {Promise<void>}\n */\n setRate(options: AssetRate): Promise<void>;\n\n /**\n * Set the current time of an audio file\n * @since 6.5.0\n * @param option {@link AssetSetTime}\n * @returns {Promise<void>}\n */\n setCurrentTime(options: AssetSetTime): Promise<void>;\n\n /**\n * Get the current time of an audio file\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns {Promise<{ currentTime: number }>}\n */\n getCurrentTime(options: Assets): Promise<{ currentTime: number }>;\n\n /**\n * Get the duration of an audio file in seconds\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns {Promise<{ duration: number }>}\n */\n getDuration(options: Assets): Promise<{ duration: number }>;\n\n /**\n * Check if an audio file is playing\n *\n * @since 5.0.0\n * @param option {@link Assets}\n * @returns {Promise<boolean>}\n */\n isPlaying(options: Assets): Promise<{ isPlaying: boolean }>;\n\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 /**\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 * Listen for playback state changes, including notification and lock-screen transport controls.\n * Emitted by Android and iOS. The current Web implementation does not emit this event.\n *\n * @since 8.3.15\n * return {@link PlaybackStateEvent}\n */\n addListener(eventName: 'playbackState', listenerFunc: PlaybackStateListener): 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 * Set debug mode logging\n * @since 6.5.0\n * @param options - Options to enable or disable debug mode\n */\n setDebugMode(options: { enabled: boolean }): 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"]}
@@ -8,11 +8,17 @@ enum MyError: Error {
8
8
  case runtimeError(String)
9
9
  }
10
10
 
11
+ private enum PlaybackStateValue: String {
12
+ case playing
13
+ case paused
14
+ case stopped
15
+ }
16
+
11
17
  // swiftlint:disable file_length
12
18
  @objc(NativeAudio)
13
19
  // swiftlint:disable:next type_body_length
14
20
  public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
15
- private let pluginVersion: String = "8.4.0"
21
+ private let pluginVersion: String = "8.4.1"
16
22
  public let identifier = "NativeAudio"
17
23
  public let jsName = "NativeAudio"
18
24
  public let pluginMethods: [CAPPluginMethod] = [
@@ -172,9 +178,58 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
172
178
  }
173
179
  }
174
180
 
181
+ private func resolvePlaybackState(assetId: String, audioAsset: AudioAsset?) -> PlaybackStateValue {
182
+ if let audioAsset, audioAsset.isPlaying() {
183
+ return .playing
184
+ }
185
+ if let data = audioAssetData[assetId],
186
+ data["timeBeforePause"] != nil || data["volumeBeforePause"] != nil {
187
+ return .paused
188
+ }
189
+ if currentlyPlayingAssetId == assetId {
190
+ return .paused
191
+ }
192
+ return .stopped
193
+ }
194
+
195
+ private func notifyPlaybackState(assetId: String, reason: String, state: PlaybackStateValue? = nil, audioAsset: AudioAsset? = nil) {
196
+ let emit = {
197
+ let asset = audioAsset ?? self.audioList[assetId] as? AudioAsset
198
+ let resolvedState = state ?? self.resolvePlaybackState(assetId: assetId, audioAsset: asset)
199
+ var data: [String: Any] = [
200
+ "assetId": assetId,
201
+ "state": resolvedState.rawValue,
202
+ "reason": reason,
203
+ "isPlaying": resolvedState == .playing
204
+ ]
205
+ if let asset {
206
+ data["currentTime"] = asset.getCurrentTime()
207
+ let duration = asset.getDuration()
208
+ if duration.isFinite {
209
+ data["duration"] = duration
210
+ }
211
+ }
212
+ self.notifyListeners("playbackState", data: data)
213
+ }
214
+
215
+ if DispatchQueue.getSpecific(key: queueKey) != nil || DispatchQueue.getSpecific(key: audioQueueContextKey) == true {
216
+ emit()
217
+ } else {
218
+ audioQueue.async(execute: emit)
219
+ }
220
+ }
221
+
222
+ internal func handlePlaybackCompletion(assetId: String, audioAsset: AudioAsset? = nil) {
223
+ if currentlyPlayingAssetId == assetId {
224
+ currentlyPlayingAssetId = nil
225
+ clearNowPlayingInfo()
226
+ }
227
+ notifyPlaybackState(assetId: assetId, reason: "complete", state: .stopped, audioAsset: audioAsset)
228
+ }
229
+
175
230
  /// Must be called on `audioQueue`. If `timeBeforePause` is stored, clears it and seeks (async for remote) before running `resume` + Now Playing refresh.
176
231
  /// Mirrors `resume(_:)` (non–fade-in path): restores `volumeBeforePause` via `setVolume`, clears that key from `audioAssetData`, then `resume()`.
177
- private func resumeAssetFromStoredPausePositionIfNeeded(assetId: String, asset: AudioAsset) {
232
+ private func resumeAssetFromStoredPausePositionIfNeeded(assetId: String, asset: AudioAsset, reason: String = "resume") {
178
233
  var restoredTime: TimeInterval?
179
234
  if var data = audioAssetData[assetId],
180
235
  let time = data["timeBeforePause"] as? TimeInterval {
@@ -198,10 +253,14 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
198
253
  self.audioAssetData[assetId] = data
199
254
  }
200
255
  asset.resume()
201
- updateNowPlayingInfo(audioId: assetId, audioAsset: asset)
256
+ if self.showNotification {
257
+ self.currentlyPlayingAssetId = assetId
258
+ self.updateNowPlayingInfo(audioId: assetId, audioAsset: asset)
259
+ }
260
+ self.notifyPlaybackState(assetId: assetId, reason: reason, state: .playing, audioAsset: asset)
202
261
  }
203
- if let t = restoredTime {
204
- asset.setCurrentTime(time: t) { [weak self] in
262
+ if let resumeTime = restoredTime {
263
+ asset.setCurrentTime(time: resumeTime) { [weak self] in
205
264
  guard let self else { return }
206
265
  audioQueue.async(flags: .barrier, execute: resumeAndRefreshNowPlaying)
207
266
  }
@@ -226,7 +285,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
226
285
  }
227
286
 
228
287
  if !asset.isPlaying() {
229
- self.resumeAssetFromStoredPausePositionIfNeeded(assetId: assetId, asset: asset)
288
+ self.resumeAssetFromStoredPausePositionIfNeeded(assetId: assetId, asset: asset, reason: "remotePlay")
230
289
  }
231
290
  }
232
291
  return .success
@@ -251,6 +310,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
251
310
 
252
311
  asset.pause()
253
312
  self.updatePlaybackState(isPlaying: false, elapsedTime: timeBeforePause, duration: asset.getDuration())
313
+ self.notifyPlaybackState(assetId: assetId, reason: "remotePause", state: .paused, audioAsset: asset)
254
314
  }
255
315
  return .success
256
316
  }
@@ -280,6 +340,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
280
340
  duration: duration
281
341
  )
282
342
  }
343
+ self.notifyPlaybackState(assetId: assetId, reason: "remoteStop", state: .stopped, audioAsset: asset)
283
344
  }
284
345
  return .success
285
346
  }
@@ -304,8 +365,9 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
304
365
 
305
366
  asset.pause()
306
367
  self.updatePlaybackState(isPlaying: false, elapsedTime: timeBeforePause, duration: asset.getDuration())
368
+ self.notifyPlaybackState(assetId: assetId, reason: "remotePause", state: .paused, audioAsset: asset)
307
369
  } else {
308
- self.resumeAssetFromStoredPausePositionIfNeeded(assetId: assetId, asset: asset)
370
+ self.resumeAssetFromStoredPausePositionIfNeeded(assetId: assetId, asset: asset, reason: "remotePlay")
309
371
  }
310
372
  }
311
373
  return .success
@@ -713,7 +775,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
713
775
  }
714
776
 
715
777
  // Set up completion handler
716
- asset.onComplete = { [weak self] in
778
+ asset.onComplete = {
717
779
  cleanupHandler()
718
780
  }
719
781
 
@@ -728,6 +790,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
728
790
  self.updateNowPlayingInfo(audioId: assetId, audioAsset: asset)
729
791
  self.updatePlaybackState(isPlaying: true)
730
792
  }
793
+ self.notifyPlaybackState(assetId: assetId, reason: "playOnce", state: .playing, audioAsset: asset)
731
794
  }
732
795
 
733
796
  // Return the generated assetId
@@ -799,14 +862,13 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
799
862
  // Instead, check if all players are done and clear Now Playing if this asset was current
800
863
  audioQueue.async { [weak self] in
801
864
  guard let self = self else { return }
865
+ var completedAssetId: String?
802
866
 
803
867
  // Find which asset this player belongs to; if it was the currently playing one, clear notification
804
868
  for (audioId, asset) in self.audioList {
805
869
  if let audioAsset = asset as? AudioAsset, audioAsset.channels.contains(player) {
806
- if self.currentlyPlayingAssetId == audioId {
807
- self.currentlyPlayingAssetId = nil
808
- self.clearNowPlayingInfo()
809
- }
870
+ completedAssetId = audioId
871
+ self.handlePlaybackCompletion(assetId: audioId, audioAsset: audioAsset)
810
872
  break
811
873
  }
812
874
  }
@@ -823,7 +885,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
823
885
  // Only end the session if no more assets are playing
824
886
  if !hasPlayingAssets {
825
887
  // If we didn't find the asset above (e.g. playOnce already removed it), clear notification when nothing is playing
826
- if self.currentlyPlayingAssetId != nil {
888
+ if completedAssetId == nil, self.currentlyPlayingAssetId != nil {
827
889
  self.currentlyPlayingAssetId = nil
828
890
  self.clearNowPlayingInfo()
829
891
  }
@@ -890,6 +952,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
890
952
  self.updateNowPlayingInfo(audioId: audioId, audioAsset: audioAsset)
891
953
  self.updatePlaybackState(isPlaying: true)
892
954
  }
955
+ self.notifyPlaybackState(assetId: audioId, reason: "play", state: .playing, audioAsset: audioAsset)
893
956
  call.resolve()
894
957
  }
895
958
  }
@@ -971,6 +1034,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
971
1034
  }
972
1035
  }
973
1036
 
1037
+ // swiftlint:disable:next function_body_length
974
1038
  @objc func resume(_ call: CAPPluginCall) {
975
1039
  let audioId = call.getString(Constant.AssetIdKey) ?? ""
976
1040
  audioQueue.sync {
@@ -1015,13 +1079,15 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1015
1079
  self.audioAssetData[audioAsset.assetId] = data
1016
1080
  }
1017
1081
  if self.showNotification {
1082
+ self.currentlyPlayingAssetId = audioId
1018
1083
  self.updateNowPlayingInfo(audioId: audioId, audioAsset: audioAsset)
1019
1084
  }
1085
+ self.notifyPlaybackState(assetId: audioId, reason: "resume", state: .playing, audioAsset: audioAsset)
1020
1086
  call.resolve()
1021
1087
  }
1022
1088
 
1023
- if let t = restoredTime {
1024
- audioAsset.setCurrentTime(time: t) { [weak self] in
1089
+ if let resumeTime = restoredTime {
1090
+ audioAsset.setCurrentTime(time: resumeTime) { [weak self] in
1025
1091
  guard let self else { return }
1026
1092
  self.audioQueue.async(flags: .barrier, execute: finishResume)
1027
1093
  }
@@ -1064,6 +1130,9 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1064
1130
  }
1065
1131
 
1066
1132
  self.endSession()
1133
+ if !fadeOut {
1134
+ self.notifyPlaybackState(assetId: audioAsset.assetId, reason: "pause", state: .paused, audioAsset: audioAsset)
1135
+ }
1067
1136
  call.resolve()
1068
1137
  }
1069
1138
  }
@@ -1120,6 +1189,13 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1120
1189
  }
1121
1190
 
1122
1191
  self.endSession()
1192
+ if !fadeOut {
1193
+ if let audioAsset = self.audioList[audioId] as? AudioAsset {
1194
+ self.notifyPlaybackState(assetId: audioId, reason: "stop", state: .stopped, audioAsset: audioAsset)
1195
+ } else {
1196
+ self.notifyPlaybackState(assetId: audioId, reason: "stop", state: .stopped)
1197
+ }
1198
+ }
1123
1199
  call.resolve()
1124
1200
  } catch {
1125
1201
  call.reject(error.localizedDescription)
@@ -1137,6 +1213,12 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1137
1213
  }
1138
1214
 
1139
1215
  audioAsset.loop()
1216
+ if self.showNotification {
1217
+ self.currentlyPlayingAssetId = audioAsset.assetId
1218
+ self.updateNowPlayingInfo(audioId: audioAsset.assetId, audioAsset: audioAsset)
1219
+ self.updatePlaybackState(isPlaying: true)
1220
+ }
1221
+ self.notifyPlaybackState(assetId: audioAsset.assetId, reason: "loop", state: .playing, audioAsset: audioAsset)
1140
1222
  call.resolve()
1141
1223
  }
1142
1224
  }
@@ -1552,6 +1634,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1552
1634
  call.resolve()
1553
1635
  }
1554
1636
 
1637
+ // swiftlint:disable cyclomatic_complexity
1555
1638
  /// Updates the system Now Playing information for the specified audio asset.
1556
1639
  ///
1557
1640
  /// Looks up stored metadata for `audioId` and publishes title, artist, album, artwork (if provided),
@@ -1613,6 +1696,7 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1613
1696
  MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
1614
1697
  }
1615
1698
  }
1699
+ // swiftlint:enable cyclomatic_complexity
1616
1700
 
1617
1701
  /// Clears the Now Playing info when the plugin is no longer the active notifier.
1618
1702
  private func clearNowPlayingInfo() {
@@ -1631,6 +1715,11 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1631
1715
  if self.showNotification && self.currentlyPlayingAssetId == assetId {
1632
1716
  self.updatePlaybackState(isPlaying: false, elapsedTime: elapsedTime, duration: duration)
1633
1717
  }
1718
+ if let audioAsset = self.audioList[assetId] as? AudioAsset {
1719
+ self.notifyPlaybackState(assetId: assetId, reason: "pause", state: .paused, audioAsset: audioAsset)
1720
+ } else {
1721
+ self.notifyPlaybackState(assetId: assetId, reason: "pause", state: .paused)
1722
+ }
1634
1723
  }
1635
1724
  }
1636
1725
 
@@ -1641,6 +1730,11 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
1641
1730
  if self.showNotification && self.currentlyPlayingAssetId == assetId {
1642
1731
  self.updatePlaybackState(isPlaying: false, elapsedTime: elapsedTime, duration: duration)
1643
1732
  }
1733
+ if let audioAsset = self.audioList[assetId] as? AudioAsset {
1734
+ self.notifyPlaybackState(assetId: assetId, reason: "stop", state: .stopped, audioAsset: audioAsset)
1735
+ } else {
1736
+ self.notifyPlaybackState(assetId: assetId, reason: "stop", state: .stopped)
1737
+ }
1644
1738
  }
1645
1739
  }
1646
1740
 
@@ -1,5 +1,6 @@
1
1
  @preconcurrency import AVFoundation
2
2
 
3
+ // swiftlint:disable file_length
3
4
  // swiftlint:disable:next type_body_length
4
5
  public class RemoteAudioAsset: AudioAsset {
5
6
  var playerItems: [AVPlayerItem] = []
@@ -89,6 +90,7 @@ public class RemoteAudioAsset: AudioAsset {
89
90
  guard let self else { return }
90
91
  self.owner?.notifyListeners("complete", data: ["assetId": self.assetId])
91
92
  self.dispatchedCompleteMap[self.assetId] = true
93
+ self.owner?.handlePlaybackCompletion(assetId: self.assetId, audioAsset: self)
92
94
  self.onComplete?()
93
95
  }
94
96
  }
@@ -153,11 +155,11 @@ public class RemoteAudioAsset: AudioAsset {
153
155
  let lowerBound = max(time, 0)
154
156
  let validTime: TimeInterval
155
157
  if let item = player.currentItem {
156
- let d = item.duration
157
- if d == .indefinite || !d.isValid {
158
+ let itemDuration = item.duration
159
+ if itemDuration == .indefinite || !itemDuration.isValid {
158
160
  validTime = lowerBound
159
161
  } else {
160
- let durationSeconds = d.seconds
162
+ let durationSeconds = itemDuration.seconds
161
163
  if durationSeconds.isFinite && durationSeconds > 0 {
162
164
  validTime = min(lowerBound, durationSeconds)
163
165
  } else {
@@ -400,3 +402,4 @@ public class RemoteAudioAsset: AudioAsset {
400
402
  }
401
403
 
402
404
  }
405
+ // swiftlint:enable file_length
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/native-audio",
3
- "version": "8.4.0",
3
+ "version": "8.4.1",
4
4
  "description": "A native plugin for native audio engine",
5
5
  "license": "MPL-2.0",
6
6
  "main": "dist/plugin.cjs.js",
@@ -36,23 +36,29 @@
36
36
  ],
37
37
  "scripts": {
38
38
  "capacitor:sync:after": "node scripts/configure-dependencies.js",
39
- "verify": "npm run verify:ios && npm run verify:android && npm run verify:web",
39
+ "verify": "bun run verify:ios && bun run verify:android && bun run verify:web",
40
40
  "verify:ios": "xcodebuild -scheme CapgoNativeAudio -destination generic/platform=iOS",
41
41
  "verify:android": "cd android && ./gradlew clean build test && cd ..",
42
- "verify:web": "npm run build",
43
- "test": "npm run test:ios",
42
+ "verify:web": "bun run build",
43
+ "test": "bun run test:ios",
44
44
  "test:ios": "cd ios && xcodebuild test -workspace Plugin.xcworkspace -scheme Plugin -destination 'platform=iOS Simulator,name=iPhone 16' && cd ..",
45
- "lint": "npm run eslint && npm run prettier -- --check && npm run swiftlint -- lint",
46
- "fmt": "npm run eslint -- --fix && npm run prettier -- --write && npm run swiftlint -- --fix --format",
45
+ "lint": "bun run eslint && bun run prettier -- --check && bun run swiftlint -- lint",
46
+ "fmt": "bun run eslint -- --fix && bun run prettier -- --write && bun run swiftlint -- --fix --format",
47
47
  "eslint": "eslint . --ext .ts",
48
48
  "prettier": "prettier-pretty-check \"**/*.{css,html,ts,js,java}\" --plugin=prettier-plugin-java",
49
49
  "swiftlint": "node-swiftlint",
50
50
  "docgen": "docgen --api NativeAudio --output-readme README.md --output-json dist/docs.json",
51
- "build": "npm run clean && npm run docgen && npm run build:scripts && tsc && rollup -c rollup.config.mjs",
51
+ "build": "bun run clean && bun run docgen && bun run build:scripts && tsc && rollup -c rollup.config.mjs",
52
52
  "build:scripts": "tsc -p scripts/tsconfig.json",
53
53
  "clean": "rimraf ./dist",
54
54
  "watch": "tsc --watch",
55
- "prepublishOnly": "npm run build"
55
+ "example:install": "cd example-app && bun install",
56
+ "example:build": "cd example-app && bun run build",
57
+ "example:sync:android": "cd example-app && bun run sync:android",
58
+ "example:sync:ios": "cd example-app && bun run sync:ios",
59
+ "test:e2e:android": "maestro test .maestro/android/basic-features.yaml",
60
+ "test:e2e:ios": "maestro test .maestro/ios/basic-features.yaml",
61
+ "prepublishOnly": "bun run build"
56
62
  },
57
63
  "devDependencies": {
58
64
  "@capacitor/android": "^8.0.0",