@capgo/native-audio 7.9.9 → 7.9.11

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
@@ -136,6 +136,19 @@ No configuration required for this plugin.
136
136
 
137
137
  You can display audio playback information in the system notification center. This is perfect for music players, podcast apps, and any app that plays audio in the background.
138
138
 
139
+ > **⚠️ Important iOS Behavior**
140
+ >
141
+ > Enabling `showNotification: true` changes how your app's audio interacts with other apps on iOS:
142
+ >
143
+ > - **With notifications enabled** (showNotification: true): Your audio will **interrupt** other apps' audio (like Spotify, Apple Music, etc.). This is required for Now Playing controls to appear in Control Center and on the lock screen.
144
+ > - **With notifications disabled** (showNotification: false): Your audio will **mix** with other apps' audio, allowing background music to continue playing.
145
+ >
146
+ > **When to use each:**
147
+ > - ✅ Use `showNotification: true` for: Music players, podcast apps, audiobook players (primary audio source)
148
+ > - ❌ Use `showNotification: false` for: Sound effects, notification sounds, secondary audio where mixing is preferred
149
+ >
150
+ > See [Issue #202](https://github.com/Cap-go/capacitor-native-audio/issues/202) for technical details.
151
+
139
152
  **Step 1: Configure the plugin with notification support**
140
153
 
141
154
  ```typescript
@@ -193,6 +206,7 @@ The media control buttons automatically handle:
193
206
  - All metadata fields are optional
194
207
  - Artwork can be a local file path or remote URL
195
208
  - The notification only appears when `showNotification: true` is set in configure()
209
+ - ⚠️ **iOS:** Enabling notifications will interrupt other apps' audio (see warning above)
196
210
  - iOS: Uses MPNowPlayingInfoCenter with MPRemoteCommandCenter
197
211
  - Android: Uses MediaSession with NotificationCompat.MediaStyle
198
212
 
@@ -674,29 +688,37 @@ Use this when you need to ensure compatibility with other audio plugins
674
688
 
675
689
  #### ConfigureOptions
676
690
 
677
- | Prop | Type | Description |
678
- | ---------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
679
- | **`fade`** | <code>boolean</code> | Play the audio with Fade effect, only available for IOS |
680
- | **`focus`** | <code>boolean</code> | focus the audio with Audio Focus |
681
- | **`background`** | <code>boolean</code> | Play the audio in the background |
682
- | **`ignoreSilent`** | <code>boolean</code> | Ignore silent mode, works only on iOS setting this will nuke other audio apps |
683
- | **`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 |
691
+ | Prop | Type | Description |
692
+ | ---------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
693
+ | **`fade`** | <code>boolean</code> | Play the audio with Fade effect, only available for IOS |
694
+ | **`focus`** | <code>boolean</code> | focus the audio with Audio Focus |
695
+ | **`background`** | <code>boolean</code> | Play the audio in the background |
696
+ | **`ignoreSilent`** | <code>boolean</code> | Ignore silent mode, works only on iOS setting this will nuke other audio apps |
697
+ | **`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. |
684
698
 
685
699
 
686
700
  #### PreloadOptions
687
701
 
688
- | Prop | Type | Description |
689
- | -------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
690
- | **`assetPath`** | <code>string</code> | Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://) Supported formats: - MP3, WAV (all platforms) - M3U8/HLS streams (iOS and Android) |
691
- | **`assetId`** | <code>string</code> | Asset Id, unique identifier of the file |
692
- | **`volume`** | <code>number</code> | Volume of the audio, between 0.1 and 1.0 |
693
- | **`audioChannelNum`** | <code>number</code> | Audio channel number, default is 1 |
694
- | **`isUrl`** | <code>boolean</code> | Is the audio file a URL, pass true if assetPath is a `file://` url or a streaming URL (m3u8) |
695
- | **`notificationMetadata`** | <code><a href="#notificationmetadata">NotificationMetadata</a></code> | Metadata to display in the notification center when audio is playing Only used when showNotification is enabled in configure() |
702
+ | Prop | Type | Description | Since |
703
+ | -------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ |
704
+ | **`assetPath`** | <code>string</code> | Path to the audio file, relative path of the file, absolute url (file://) or remote url (https://) Supported formats: - MP3, WAV (all platforms) - M3U8/HLS streams (iOS and Android) | |
705
+ | **`assetId`** | <code>string</code> | Asset Id, unique identifier of the file | |
706
+ | **`volume`** | <code>number</code> | Volume of the audio, between 0.1 and 1.0 | |
707
+ | **`audioChannelNum`** | <code>number</code> | Audio channel number, default is 1 | |
708
+ | **`isUrl`** | <code>boolean</code> | Is the audio file a URL, pass true if assetPath is a `file://` url or a streaming URL (m3u8) | |
709
+ | **`notificationMetadata`** | <code><a href="#notificationmetadata">NotificationMetadata</a></code> | Metadata to display in the notification center when audio is playing. Only used when `showNotification: true` is set in `configure()`. See {@link <a href="#configureoptions">ConfigureOptions.showNotification</a>} for important details about how this affects audio mixing behavior on iOS. | |
710
+ | **`headers`** | <code><a href="#record">Record</a>&lt;string, string&gt;</code> | Custom HTTP headers to include when fetching remote audio files. Only used when isUrl is true and assetPath is a remote URL (http/https). Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' } | 7.10.0 |
696
711
 
697
712
 
698
713
  #### NotificationMetadata
699
714
 
715
+ Metadata to display in the notification center, Control Center (iOS), and lock screen
716
+ when `showNotification` is enabled in `configure()`.
717
+
718
+ Note: This metadata will only be displayed if `showNotification: true` is set in the
719
+ `configure()` method. See {@link <a href="#configureoptions">ConfigureOptions.showNotification</a>} for important
720
+ behavior details about audio mixing on iOS.
721
+
700
722
  | Prop | Type | Description |
701
723
  | ---------------- | ------------------- | ----------------------------------------------------- |
702
724
  | **`title`** | <code>string</code> | The title to display in the notification center |
@@ -737,6 +759,13 @@ Use this when you need to ensure compatibility with other audio plugins
737
759
  ### Type Aliases
738
760
 
739
761
 
762
+ #### Record
763
+
764
+ Construct a type with a set of properties K of type T
765
+
766
+ <code>{
740
767
  [P in K]: T;
741
768
  }</code>
769
+
770
+
742
771
  #### CompletedListener
743
772
 
744
773
  <code>(state: <a href="#completedevent">CompletedEvent</a>): void</code>
@@ -64,5 +64,5 @@ dependencies {
64
64
  implementation 'androidx.media3:media3-common:1.8.0'
65
65
  // Media notification support
66
66
  implementation 'androidx.media:media:1.7.1'
67
- implementation 'androidx.core:core:1.17.0'
67
+ implementation 'androidx.core:core:1.13.1'
68
68
  }
@@ -50,6 +50,7 @@ import java.net.URI;
50
50
  import java.net.URL;
51
51
  import java.util.ArrayList;
52
52
  import java.util.HashMap;
53
+ import java.util.Iterator;
53
54
  import java.util.Map;
54
55
 
55
56
  @UnstableApi
@@ -644,14 +645,40 @@ public class NativeAudio extends Plugin implements AudioManager.OnAudioFocusChan
644
645
  if (uri.getScheme() != null && (uri.getScheme().equals("http") || uri.getScheme().equals("https"))) {
645
646
  // Remote URL
646
647
  Log.d("AudioPlugin", "Debug: Remote URL detected: " + uri.toString());
648
+
649
+ // Extract headers if provided
650
+ Map<String, String> requestHeaders = null;
651
+ JSObject headersObj = call.getObject("headers");
652
+ if (headersObj != null) {
653
+ requestHeaders = new HashMap<>();
654
+ for (Iterator<String> it = headersObj.keys(); it.hasNext(); ) {
655
+ String key = it.next();
656
+ try {
657
+ String value = headersObj.getString(key);
658
+ if (value != null) {
659
+ requestHeaders.put(key, value);
660
+ }
661
+ } catch (Exception e) {
662
+ Log.w("AudioPlugin", "Skipping non-string header: " + key);
663
+ }
664
+ }
665
+ }
666
+
647
667
  if (assetPath.endsWith(".m3u8")) {
648
668
  // HLS Stream - resolve immediately since it's a stream
649
- StreamAudioAsset streamAudioAsset = new StreamAudioAsset(this, audioId, uri, volume);
669
+ StreamAudioAsset streamAudioAsset = new StreamAudioAsset(this, audioId, uri, volume, requestHeaders);
650
670
  audioAssetList.put(audioId, streamAudioAsset);
651
671
  call.resolve(status);
652
672
  } else {
653
673
  // Regular remote audio
654
- RemoteAudioAsset remoteAudioAsset = new RemoteAudioAsset(this, audioId, uri, audioChannelNum, volume);
674
+ RemoteAudioAsset remoteAudioAsset = new RemoteAudioAsset(
675
+ this,
676
+ audioId,
677
+ uri,
678
+ audioChannelNum,
679
+ volume,
680
+ requestHeaders
681
+ );
655
682
  remoteAudioAsset.setCompletionListener(this::dispatchComplete);
656
683
  audioAssetList.put(audioId, remoteAudioAsset);
657
684
  call.resolve(status);
@@ -18,6 +18,7 @@ import androidx.media3.exoplayer.source.MediaSource;
18
18
  import androidx.media3.exoplayer.source.ProgressiveMediaSource;
19
19
  import java.io.File;
20
20
  import java.util.ArrayList;
21
+ import java.util.Map;
21
22
 
22
23
  @UnstableApi
23
24
  public class RemoteAudioAsset extends AudioAsset {
@@ -36,13 +37,16 @@ public class RemoteAudioAsset extends AudioAsset {
36
37
  private float initialVolume;
37
38
  private Handler currentTimeHandler;
38
39
  private Runnable currentTimeRunnable;
40
+ private final Map<String, String> headers;
39
41
 
40
- public RemoteAudioAsset(NativeAudio owner, String assetId, Uri uri, int audioChannelNum, float volume) throws Exception {
42
+ public RemoteAudioAsset(NativeAudio owner, String assetId, Uri uri, int audioChannelNum, float volume, Map<String, String> headers)
43
+ throws Exception {
41
44
  super(owner, assetId, null, 0, volume);
42
45
  this.uri = uri;
43
46
  this.volume = volume;
44
47
  this.initialVolume = volume;
45
48
  this.players = new ArrayList<>();
49
+ this.headers = headers;
46
50
 
47
51
  if (audioChannelNum < 1) {
48
52
  audioChannelNum = 1;
@@ -87,12 +91,17 @@ public class RemoteAudioAsset extends AudioAsset {
87
91
  );
88
92
  }
89
93
 
90
- // Create cached data source factory
94
+ // Create cached data source factory with custom headers
91
95
  DefaultHttpDataSource.Factory httpDataSourceFactory = new DefaultHttpDataSource.Factory()
92
96
  .setAllowCrossProtocolRedirects(true)
93
97
  .setConnectTimeoutMs(15000)
94
98
  .setReadTimeoutMs(15000);
95
99
 
100
+ // Add custom headers if provided
101
+ if (headers != null && !headers.isEmpty()) {
102
+ httpDataSourceFactory.setDefaultRequestProperties(headers);
103
+ }
104
+
96
105
  CacheDataSource.Factory cacheDataSourceFactory = new CacheDataSource.Factory()
97
106
  .setCache(cache)
98
107
  .setUpstreamDataSourceFactory(httpDataSourceFactory)
@@ -301,10 +310,46 @@ public class RemoteAudioAsset extends AudioAsset {
301
310
 
302
311
  @Override
303
312
  public void unload() throws Exception {
304
- for (ExoPlayer player : players) {
305
- player.release();
313
+ if (Looper.myLooper() == Looper.getMainLooper()) {
314
+ // Synchronous cleanup when already on the main thread
315
+ stopCurrentTimeUpdates();
316
+ for (ExoPlayer player : new ArrayList<>(players)) {
317
+ try {
318
+ player.release();
319
+ } catch (Exception e) {
320
+ Log.w(TAG, "Error releasing player", e);
321
+ }
322
+ }
323
+ players.clear();
324
+ isPrepared = false;
325
+ playIndex = 0;
326
+ return;
327
+ }
328
+ // Ensure cleanup completes before returning when called off the main thread
329
+ final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1);
330
+ new Handler(Looper.getMainLooper()).post(() -> {
331
+ try {
332
+ stopCurrentTimeUpdates();
333
+ for (ExoPlayer player : new ArrayList<>(players)) {
334
+ try {
335
+ player.release();
336
+ } catch (Exception e) {
337
+ Log.w(TAG, "Error releasing player", e);
338
+ }
339
+ }
340
+ players.clear();
341
+ isPrepared = false;
342
+ playIndex = 0;
343
+ } finally {
344
+ latch.countDown();
345
+ }
346
+ });
347
+ try {
348
+ // Don't block forever; adjust timeout as needed
349
+ latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
350
+ } catch (InterruptedException ie) {
351
+ Thread.currentThread().interrupt();
306
352
  }
307
- players.clear();
308
353
  }
309
354
 
310
355
  @Override
@@ -27,12 +27,15 @@ public class StreamAudioAsset extends AudioAsset {
27
27
  private static final float FADE_STEP = 0.05f;
28
28
  private static final int FADE_DELAY_MS = 80; // 80ms between steps
29
29
  private static final long LIVE_OFFSET_MS = 5000; // 5 seconds behind live
30
+ private final java.util.Map<String, String> headers;
30
31
 
31
- public StreamAudioAsset(NativeAudio owner, String assetId, Uri uri, float volume) throws Exception {
32
+ public StreamAudioAsset(NativeAudio owner, String assetId, Uri uri, float volume, java.util.Map<String, String> headers)
33
+ throws Exception {
32
34
  super(owner, assetId, null, 0, volume);
33
35
  this.uri = uri;
34
36
  this.volume = volume;
35
37
  this.initialVolume = volume;
38
+ this.headers = headers;
36
39
 
37
40
  createPlayer();
38
41
  }
@@ -74,6 +77,11 @@ public class StreamAudioAsset extends AudioAsset {
74
77
  .setReadTimeoutMs(15000)
75
78
  .setUserAgent("ExoPlayer");
76
79
 
80
+ // Add custom headers if provided
81
+ if (headers != null && !headers.isEmpty()) {
82
+ httpDataSourceFactory.setDefaultRequestProperties(headers);
83
+ }
84
+
77
85
  HlsMediaSource mediaSource = new HlsMediaSource.Factory(httpDataSourceFactory)
78
86
  .setAllowChunklessPreparation(true)
79
87
  .setTimestampAdjusterInitializationTimeoutMs(LIVE_OFFSET_MS) // 30 seconds timeout
@@ -216,6 +224,11 @@ public class StreamAudioAsset extends AudioAsset {
216
224
  .setReadTimeoutMs(15000)
217
225
  .setUserAgent("ExoPlayer");
218
226
 
227
+ // Add custom headers if provided
228
+ if (headers != null && !headers.isEmpty()) {
229
+ httpDataSourceFactory.setDefaultRequestProperties(headers);
230
+ }
231
+
219
232
  HlsMediaSource mediaSource = new HlsMediaSource.Factory(httpDataSourceFactory)
220
233
  .setAllowChunklessPreparation(true)
221
234
  .setTimestampAdjusterInitializationTimeoutMs(LIVE_OFFSET_MS)
@@ -461,6 +474,11 @@ public class StreamAudioAsset extends AudioAsset {
461
474
  .setReadTimeoutMs(15000)
462
475
  .setUserAgent("ExoPlayer");
463
476
 
477
+ // Add custom headers if provided
478
+ if (headers != null && !headers.isEmpty()) {
479
+ httpDataSourceFactory.setDefaultRequestProperties(headers);
480
+ }
481
+
464
482
  HlsMediaSource mediaSource = new HlsMediaSource.Factory(httpDataSourceFactory)
465
483
  .setAllowChunklessPreparation(true)
466
484
  .setTimestampAdjusterInitializationTimeoutMs(LIVE_OFFSET_MS)
package/dist/docs.json CHANGED
@@ -659,8 +659,13 @@
659
659
  },
660
660
  {
661
661
  "name": "showNotification",
662
- "tags": [],
663
- "docs": "Show audio playback in the notification center (iOS and Android)\nWhen enabled, displays audio metadata (title, artist, album, artwork) in the system notification",
662
+ "tags": [
663
+ {
664
+ "text": "https ://github.com/Cap-go/capacitor-native-audio/issues/202",
665
+ "name": "see"
666
+ }
667
+ ],
668
+ "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.",
664
669
  "complexTypes": [],
665
670
  "type": "boolean | undefined"
666
671
  }
@@ -710,19 +715,38 @@
710
715
  },
711
716
  {
712
717
  "name": "notificationMetadata",
713
- "tags": [],
714
- "docs": "Metadata to display in the notification center when audio is playing\nOnly used when showNotification is enabled in configure()",
718
+ "tags": [
719
+ {
720
+ "text": "NotificationMetadata",
721
+ "name": "see"
722
+ }
723
+ ],
724
+ "docs": "Metadata to display in the notification center when audio is playing.\nOnly used when `showNotification: true` is set in `configure()`.\n\nSee {@link ConfigureOptions.showNotification} for important details about\nhow this affects audio mixing behavior on iOS.",
715
725
  "complexTypes": [
716
726
  "NotificationMetadata"
717
727
  ],
718
728
  "type": "NotificationMetadata"
729
+ },
730
+ {
731
+ "name": "headers",
732
+ "tags": [
733
+ {
734
+ "text": "7.10.0",
735
+ "name": "since"
736
+ }
737
+ ],
738
+ "docs": "Custom HTTP headers to include when fetching remote audio files.\nOnly used when isUrl is true and assetPath is a remote URL (http/https).\nExample: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }",
739
+ "complexTypes": [
740
+ "Record"
741
+ ],
742
+ "type": "Record<string, string>"
719
743
  }
720
744
  ]
721
745
  },
722
746
  {
723
747
  "name": "NotificationMetadata",
724
748
  "slug": "notificationmetadata",
725
- "docs": "",
749
+ "docs": "Metadata to display in the notification center, Control Center (iOS), and lock screen\nwhen `showNotification` is enabled in `configure()`.\n\nNote: This metadata will only be displayed if `showNotification: true` is set in the\n`configure()` method. See {@link ConfigureOptions.showNotification} for important\nbehavior details about audio mixing on iOS.",
726
750
  "tags": [],
727
751
  "methods": [],
728
752
  "properties": [
@@ -845,6 +869,20 @@
845
869
  ],
846
870
  "enums": [],
847
871
  "typeAliases": [
872
+ {
873
+ "name": "Record",
874
+ "slug": "record",
875
+ "docs": "Construct a type with a set of properties K of type T",
876
+ "types": [
877
+ {
878
+ "text": "{\r\n [P in K]: T;\r\n}",
879
+ "complexTypes": [
880
+ "K",
881
+ "T"
882
+ ]
883
+ }
884
+ ]
885
+ },
848
886
  {
849
887
  "name": "CompletedListener",
850
888
  "slug": "completedlistener",
@@ -68,9 +68,34 @@ export interface ConfigureOptions {
68
68
  /**
69
69
  * Show audio playback in the notification center (iOS and Android)
70
70
  * When enabled, displays audio metadata (title, artist, album, artwork) in the system notification
71
+ * and Control Center (iOS) or lock screen.
72
+ *
73
+ * **Important iOS Behavior:**
74
+ * Enabling this option changes the audio session category to `.playback` with `.default` mode,
75
+ * which means your app's audio will **interrupt** other apps' audio (like background music from
76
+ * Spotify, Apple Music, etc.) instead of mixing with it. This is required for the Now Playing
77
+ * info to appear in Control Center and on the lock screen.
78
+ *
79
+ * **Trade-offs:**
80
+ * - `showNotification: true` → Shows Now Playing controls, but interrupts other audio
81
+ * - `showNotification: false` → Audio mixes with other apps, but no Now Playing controls
82
+ *
83
+ * Use this when your app is the primary audio source (music players, podcast apps, etc.).
84
+ * Disable this for secondary audio like sound effects or notification sounds where mixing
85
+ * with background music is preferred.
86
+ *
87
+ * @see https://github.com/Cap-go/capacitor-native-audio/issues/202
71
88
  */
72
89
  showNotification?: boolean;
73
90
  }
91
+ /**
92
+ * Metadata to display in the notification center, Control Center (iOS), and lock screen
93
+ * when `showNotification` is enabled in `configure()`.
94
+ *
95
+ * Note: This metadata will only be displayed if `showNotification: true` is set in the
96
+ * `configure()` method. See {@link ConfigureOptions.showNotification} for important
97
+ * behavior details about audio mixing on iOS.
98
+ */
74
99
  export interface NotificationMetadata {
75
100
  /**
76
101
  * The title to display in the notification center
@@ -115,10 +140,23 @@ export interface PreloadOptions {
115
140
  */
116
141
  isUrl?: boolean;
117
142
  /**
118
- * Metadata to display in the notification center when audio is playing
119
- * Only used when showNotification is enabled in configure()
143
+ * Metadata to display in the notification center when audio is playing.
144
+ * Only used when `showNotification: true` is set in `configure()`.
145
+ *
146
+ * See {@link ConfigureOptions.showNotification} for important details about
147
+ * how this affects audio mixing behavior on iOS.
148
+ *
149
+ * @see NotificationMetadata
120
150
  */
121
151
  notificationMetadata?: NotificationMetadata;
152
+ /**
153
+ * Custom HTTP headers to include when fetching remote audio files.
154
+ * Only used when isUrl is true and assetPath is a remote URL (http/https).
155
+ * Example: { 'x-api-key': 'abc123', 'Authorization': 'Bearer token' }
156
+ *
157
+ * @since 7.10.0
158
+ */
159
+ headers?: Record<string, string>;
122
160
  }
123
161
  export interface CurrentTimeEvent {
124
162
  /**
@@ -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 */\n showNotification?: boolean;\n}\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 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 is enabled in configure()\n */\n notificationMetadata?: NotificationMetadata;\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 * 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\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 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 * 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"]}
@@ -254,7 +254,21 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
254
254
  // Use a single audio session configuration block for better atomicity
255
255
  do {
256
256
  // Set category first
257
- if focus {
257
+ // Fix for issue #202: When showNotification is enabled, use .playback without
258
+ // .mixWithOthers or .duckOthers to allow Now Playing info to display in
259
+ // Control Center and lock screen.
260
+ //
261
+ // IMPORTANT: This is a behavior trade-off:
262
+ // - With .playback + .default mode: Now Playing info shows, but interrupts other audio
263
+ // - With .mixWithOthers or .duckOthers: Audio mixes, but no Now Playing info
264
+ //
265
+ // This is required because iOS only shows Now Playing controls for audio sessions
266
+ // that use the .playback category without mixing options. This means the app becomes
267
+ // the primary audio source and will interrupt background music from other apps.
268
+ if self.showNotification {
269
+ // Use playback category with default mode for notification support
270
+ try self.session.setCategory(AVAudioSession.Category.playback, mode: .default)
271
+ } else if focus {
258
272
  try self.session.setCategory(AVAudioSession.Category.playback, options: .duckOthers)
259
273
  } else if !ignoreSilent {
260
274
  try self.session.setCategory(AVAudioSession.Category.ambient, options: focus ? .duckOthers : .mixWithOthers)
@@ -667,7 +681,17 @@ public class NativeAudio: CAPPlugin, AVAudioPlayerDelegate, CAPBridgedPlugin {
667
681
  }
668
682
  } else {
669
683
  // Handle remote URL
670
- let remoteAudioAsset = RemoteAudioAsset(owner: self, withAssetId: audioId, withPath: assetPath, withChannels: channels, withVolume: volume, withFadeDelay: delay)
684
+ // Extract headers if provided
685
+ var headers: [String: String]?
686
+ if let headersObj = call.getObject("headers") {
687
+ headers = [:]
688
+ for (key, value) in headersObj {
689
+ if let stringValue = value as? String {
690
+ headers?[key] = stringValue
691
+ }
692
+ }
693
+ }
694
+ let remoteAudioAsset = RemoteAudioAsset(owner: self, withAssetId: audioId, withPath: assetPath, withChannels: channels, withVolume: volume, withFadeDelay: delay, withHeaders: headers)
671
695
  self.audioList[audioId] = remoteAudioAsset
672
696
  call.resolve()
673
697
  return
@@ -12,7 +12,7 @@ public class RemoteAudioAsset: AudioAsset {
12
12
  var duration: TimeInterval = 0
13
13
  var asset: AVURLAsset?
14
14
 
15
- override init(owner: NativeAudio, withAssetId assetId: String, withPath path: String!, withChannels channels: Int!, withVolume volume: Float!, withFadeDelay delay: Float!) {
15
+ init(owner: NativeAudio, withAssetId assetId: String, withPath path: String!, withChannels channels: Int!, withVolume volume: Float!, withFadeDelay delay: Float!, withHeaders headers: [String: String]?) {
16
16
  super.init(owner: owner, withAssetId: assetId, withPath: path, withChannels: channels ?? 1, withVolume: volume ?? 1.0, withFadeDelay: delay ?? 0.0)
17
17
 
18
18
  owner.executeOnAudioQueue { [weak self] in
@@ -23,7 +23,13 @@ public class RemoteAudioAsset: AudioAsset {
23
23
  return
24
24
  }
25
25
 
26
- let asset = AVURLAsset(url: url, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])
26
+ // Build AVURLAsset options with custom headers if provided
27
+ var options: [String: Any] = [AVURLAssetPreferPreciseDurationAndTimingKey: true]
28
+ if let headers = headers, !headers.isEmpty {
29
+ options["AVURLAssetHTTPHeaderFieldsKey"] = headers
30
+ }
31
+
32
+ let asset = AVURLAsset(url: url, options: options)
27
33
  self.asset = asset
28
34
 
29
35
  // Limit channels to a reasonable maximum to prevent resource issues
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/native-audio",
3
- "version": "7.9.9",
3
+ "version": "7.9.11",
4
4
  "description": "A native plugin for native audio engine",
5
5
  "license": "MPL-2.0",
6
6
  "main": "dist/plugin.cjs.js",