@octane-xplat/audio 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,8 +6,8 @@ pnpm add @octane-xplat/audio
6
6
 
7
7
  Long-form audio playback for Octane xplat apps — a queue player, not a
8
8
  sound-effect bank. iOS uses `AVPlayer`/`AVAudioSession` (interruption
9
- handling included) and Android uses `MediaPlayer`, both directly on
10
- `@nativescript/core` with no plugin dependency. Web uses an
9
+ handling included) and Android uses a package-owned Media3 playback service.
10
+ macOS uses a package-owned AVPlayer bridge. Web uses an
11
11
  `HTMLAudioElement` plus the Media Session API for system controls.
12
12
 
13
13
  ```ts
@@ -25,9 +25,10 @@ const off = player.subscribe((snapshot) => {
25
25
  Playback features vary by target and runtime state, so call
26
26
  `capabilities()` before promising behavior like lock-screen controls. It
27
27
  reports `supported`, `backgroundPlayback`, `systemControls`,
28
- `userGestureRequired`, and `interruptions`. The native entry requires
29
- iOS or Android — other targets get the web implementation or a thrown
30
- error, never a silent no-op.
28
+ `userGestureRequired`, and `interruptions`. The `macos` package condition
29
+ selects the desktop bridge without importing mobile implementations. Rebuild
30
+ the macOS app after installing this package. macOS reports system controls and
31
+ interruption recovery as unavailable; a missing bridge reports `supported: false`.
31
32
 
32
33
  ```ts
33
34
  // Continue with the player created above.
@@ -37,9 +38,32 @@ off()
37
38
  player.dispose()
38
39
  ```
39
40
 
41
+ On macOS, use an absolute local path, `file:` URL, or HTTP(S) URL. Queue
42
+ replacement rejects obsolete pending loads and stops the previous item.
43
+ Malformed media, network errors, reported output errors, and loading or
44
+ buffering stalled for 30 seconds become terminal errors. A new queue can retry;
45
+ disposal stops playback and notifications. Position, duration, and seek use
46
+ seconds. Real audible playback remains a separate qualification gate.
47
+
48
+ ```ts
49
+ import { createAudioPlayer } from '@octane-xplat/audio'
50
+
51
+ export async function playTrack(source: string) {
52
+ const player = createAudioPlayer()
53
+ try {
54
+ await player.setQueue([{ id: 'track', source }])
55
+ await player.play()
56
+ await player.seek(2.5)
57
+ await player.pause()
58
+ } finally {
59
+ player.dispose()
60
+ }
61
+ }
62
+ ```
63
+
40
64
  For short UI sounds use [`@octane-xplat/sounds`](../sounds/README.md).
41
65
 
42
66
  Guide: [Media services](../../docs/platform/media-services.md); per-target
43
- availability: [platform notes](../../docs/notes/platform-notes.md). Exercised by
67
+ availability: [platform notes](../../.agents/docs/notes/platform-notes.md). Exercised by
44
68
  the harness `MediaServices` screen
45
69
  ([`packages/app/src/MediaServices.tsrx`](../app/src/MediaServices.tsrx)).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octane-xplat/audio",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Long-form audio playback for Octane xplat",
5
5
  "keywords": [
6
6
  "android",
@@ -23,29 +23,37 @@
23
23
  "directory": "packages/audio"
24
24
  },
25
25
  "files": [
26
- "dist",
27
26
  "types",
28
27
  "src",
29
- "platforms"
28
+ "platforms",
29
+ "!src/**/*.test.*",
30
+ "!src/**/*.spec.*"
30
31
  ],
31
32
  "type": "module",
32
33
  "exports": {
33
34
  ".": {
35
+ "macos": {
36
+ "types": "./types/index.d.ts",
37
+ "default": "./src/index.macos.ts"
38
+ },
34
39
  "types": "./types/index.d.ts",
35
- "web": "./dist/web/index.js",
36
- "native": "./dist/native/index.js",
37
- "default": "./dist/native/index.js"
40
+ "web": "./src/index.web.ts",
41
+ "native": "./src/index.ts",
42
+ "default": "./src/index.ts"
38
43
  }
39
44
  },
40
45
  "publishConfig": {
41
46
  "access": "public"
42
47
  },
48
+ "dependencies": {
49
+ "@octane-xplat/platform": "0.15.0"
50
+ },
43
51
  "devDependencies": {
44
- "@nativescript-community/octane": "0.2.4",
52
+ "@nativescript-community/octane": "0.2.5",
45
53
  "@nativescript/core": "9.1.3",
46
54
  "@octanejs/vite-plugin": "0.1.61",
47
55
  "octane": "0.11.0",
48
- "tsrx-typegen": "0.2.2",
56
+ "tsrx-typegen": "0.3.0",
49
57
  "typescript": "5.9.3",
50
58
  "vite": "8.3.0"
51
59
  },
@@ -71,11 +79,21 @@
71
79
  "ios": "9.1.0"
72
80
  }
73
81
  },
82
+ "xplat": {
83
+ "macos": {
84
+ "frameworks": [
85
+ "Foundation",
86
+ "AVFoundation",
87
+ "CoreMedia"
88
+ ]
89
+ }
90
+ },
74
91
  "scripts": {
75
92
  "test": "node --test tests/*.test.mjs",
76
- "build": "vite build && vite build --mode native && pnpm typegen && node ../../scripts/check-native-dist.mjs",
77
93
  "typegen": "tsc -p tsconfig.types.json",
78
94
  "test:packed": "node tests/packed-consumer.mjs",
79
- "pack:check": "tsrx-typegen --pack-check"
95
+ "pack:check": "tsrx-typegen --pack-check",
96
+ "test:macos-runtime": "node tests/packed-consumer.mjs --macos-runtime",
97
+ "typecheck": "tsc --noEmit --strict --target esnext --module esnext --moduleResolution bundler --skipLibCheck src/audio.macos.ts"
80
98
  }
81
99
  }
@@ -2,6 +2,7 @@ package com.xplat.audio;
2
2
 
3
3
  import android.content.Context;
4
4
  import android.content.Intent;
5
+ import android.util.Log;
5
6
 
6
7
  /** Commands cross the JS/service boundary as intents so they remain ordered. */
7
8
  public final class AudioBridge {
@@ -10,17 +11,46 @@ public final class AudioBridge {
10
11
  public static final String ACTION_PAUSE = "com.xplat.audio.PAUSE";
11
12
  public static final String ACTION_SEEK = "com.xplat.audio.SEEK";
12
13
  public static final String ACTION_RELEASE = "com.xplat.audio.RELEASE";
14
+ private static final String TAG = "XplatAudio";
15
+ // The service is exported for the Media3 session — command intents are
16
+ // accepted only when they carry this process-local token, which a foreign
17
+ // app cannot observe or forge.
18
+ private static final String COMMAND_TOKEN = java.util.UUID.randomUUID().toString();
13
19
  private static volatile String snapshot = "{\"state\":\"idle\",\"currentTime\":0,\"duration\":0}";
20
+ private static volatile String pendingQueue;
14
21
 
15
22
  private AudioBridge() {}
16
23
 
17
24
  public static void dispatch(Context context, String action, String payload, int index, double seconds) {
18
25
  Intent intent = new Intent(context.getApplicationContext(), AudioPlaybackService.class);
19
26
  intent.setAction(action);
20
- if (payload != null) intent.putExtra("queue", payload);
27
+ intent.putExtra("commandToken", COMMAND_TOKEN);
28
+ // The queue JSON can exceed the ~1MB Binder extra limit — hand it to
29
+ // the service in-process and keep the intent small.
30
+ if (payload != null && ACTION_QUEUE.equals(action)) pendingQueue = payload;
21
31
  intent.putExtra("index", index);
22
32
  intent.putExtra("seconds", seconds);
23
- context.getApplicationContext().startService(intent);
33
+ try {
34
+ context.getApplicationContext().startService(intent);
35
+ } catch (RuntimeException failure) {
36
+ // A JS-initiated command while the app is backgrounded throws
37
+ // IllegalStateException — surface it through snapshot.error and
38
+ // rethrow so the caller's promise rejects.
39
+ pendingQueue = null;
40
+ Log.e(TAG, "Audio command dispatch failed", failure);
41
+ publish("{\"state\":\"error\",\"currentTime\":0,\"duration\":0,\"error\":\"audio command dispatch failed\"}");
42
+ throw failure;
43
+ }
44
+ }
45
+
46
+ static boolean isCommandIntent(Intent intent) {
47
+ return intent != null && COMMAND_TOKEN.equals(intent.getStringExtra("commandToken"));
48
+ }
49
+
50
+ static String takeQueue() {
51
+ String queue = pendingQueue;
52
+ pendingQueue = null;
53
+ return queue;
24
54
  }
25
55
 
26
56
  public static void publish(String value) { snapshot = value; }
@@ -46,10 +46,17 @@ public final class AudioPlaybackService extends MediaSessionService {
46
46
  @Override public int onStartCommand(Intent intent, int flags, int startId) {
47
47
  int result = super.onStartCommand(intent, flags, startId);
48
48
  if (intent == null || intent.getAction() == null) return result;
49
+ // com.xplat.audio.* commands execute only for this app's in-process
50
+ // bridge — the exported service is reachable by any installed app, so
51
+ // foreign command intents without the process token are dropped.
52
+ if (intent.getAction().startsWith("com.xplat.audio.") && !AudioBridge.isCommandIntent(intent)) {
53
+ return result;
54
+ }
55
+
49
56
  try {
50
57
  switch (intent.getAction()) {
51
58
  case AudioBridge.ACTION_QUEUE:
52
- setQueue(intent.getStringExtra("queue"), intent.getIntExtra("index", 0));
59
+ setQueue(AudioBridge.takeQueue(), intent.getIntExtra("index", 0));
53
60
  break;
54
61
  case AudioBridge.ACTION_PLAY: player.play(); break;
55
62
  case AudioBridge.ACTION_PAUSE: player.pause(); break;
@@ -0,0 +1,12 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ // One instance owns one AVPlayer. Calls and notifications run on the host main thread.
4
+ @interface XplatAudioPlayer : NSObject
5
+ - (void)setSource:(NSString *)source;
6
+ - (void)play;
7
+ - (void)pause;
8
+ - (void)seekSeconds:(double)seconds;
9
+ - (NSString *)snapshot;
10
+ - (void)clear;
11
+ - (void)dispose;
12
+ @end
@@ -0,0 +1,161 @@
1
+ #import "XplatAudioPlayer.h"
2
+ #import <AVFoundation/AVFoundation.h>
3
+ #import <math.h>
4
+
5
+ @interface XplatAudioPlayer ()
6
+ @property(nonatomic, strong) AVPlayer *player;
7
+ @property(nonatomic, strong) AVPlayerItem *item;
8
+ @property(nonatomic, strong) NSMutableArray *observers;
9
+ @property(nonatomic, copy) NSString *state;
10
+ @property(nonatomic, copy) NSString *failure;
11
+ @property(nonatomic) BOOL disposed;
12
+ @property(nonatomic) BOOL wantsPlayback;
13
+ @property(nonatomic) NSTimeInterval loadingSince;
14
+ @end
15
+
16
+ @implementation XplatAudioPlayer
17
+ - (instancetype)init {
18
+ if ((self = [super init])) {
19
+ _state = @"idle";
20
+ _observers = [NSMutableArray new];
21
+ }
22
+ return self;
23
+ }
24
+
25
+ - (void)releaseTrack {
26
+ for (id token in self.observers) [[NSNotificationCenter defaultCenter] removeObserver:token];
27
+ [self.observers removeAllObjects];
28
+ [self.player pause];
29
+ [self.item cancelPendingSeeks];
30
+ [self.item.asset cancelLoading];
31
+ [self.player replaceCurrentItemWithPlayerItem:nil];
32
+ self.item = nil;
33
+ self.player = nil;
34
+ self.wantsPlayback = NO;
35
+ self.loadingSince = 0;
36
+ }
37
+
38
+ - (void)fail:(NSString *)message {
39
+ [self releaseTrack];
40
+ self.failure = message.length ? message : @"Audio playback failed";
41
+ self.state = @"error";
42
+ }
43
+
44
+ - (void)setSource:(NSString *)source {
45
+ if (self.disposed) return;
46
+ [self clear];
47
+ NSURL *url = [source hasPrefix:@"/"] ? [NSURL fileURLWithPath:source] : [NSURL URLWithString:source];
48
+ NSString *scheme = url.scheme.lowercaseString;
49
+ if (!url || !([scheme isEqual:@"file"] ||
50
+ (([scheme isEqual:@"http"] || [scheme isEqual:@"https"]) && url.host.length))) {
51
+ [self fail:@"Audio source must be an absolute path, file URL, or HTTP(S) URL"];
52
+ return;
53
+ }
54
+ if (url.isFileURL && ![[NSFileManager defaultManager] isReadableFileAtPath:url.path]) {
55
+ [self fail:@"Audio file is not readable"];
56
+ return;
57
+ }
58
+ self.state = @"loading";
59
+ self.loadingSince = NSProcessInfo.processInfo.systemUptime;
60
+ self.item = [AVPlayerItem playerItemWithURL:url];
61
+ self.player = [AVPlayer playerWithPlayerItem:self.item];
62
+ __weak XplatAudioPlayer *owner = self;
63
+ AVPlayerItem *item = self.item;
64
+ NSNotificationCenter *center = NSNotificationCenter.defaultCenter;
65
+ [self.observers addObject:[center addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
66
+ object:item queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
67
+ XplatAudioPlayer *strongOwner = owner;
68
+ if (!strongOwner || strongOwner.disposed || strongOwner.item != note.object) return;
69
+ [strongOwner.player pause];
70
+ strongOwner.wantsPlayback = NO;
71
+ strongOwner.state = @"ended";
72
+ }]];
73
+ [self.observers addObject:[center addObserverForName:AVPlayerItemFailedToPlayToEndTimeNotification
74
+ object:item queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *note) {
75
+ XplatAudioPlayer *strongOwner = owner;
76
+ if (!strongOwner || strongOwner.disposed || strongOwner.item != note.object) return;
77
+ NSError *error = note.userInfo[AVPlayerItemFailedToPlayToEndTimeErrorKey];
78
+ [strongOwner fail:error.localizedDescription];
79
+ }]];
80
+ }
81
+
82
+ - (void)refresh {
83
+ if (!self.item || self.disposed || [self.state isEqual:@"ended"]) return;
84
+ if (self.item.status == AVPlayerItemStatusFailed || self.player.status == AVPlayerStatusFailed) {
85
+ [self fail:(self.item.error ?: self.player.error).localizedDescription];
86
+ return;
87
+ }
88
+ BOOL waiting = self.item.status != AVPlayerItemStatusReadyToPlay ||
89
+ (self.wantsPlayback && self.player.timeControlStatus != AVPlayerTimeControlStatusPlaying);
90
+ if (waiting) {
91
+ self.state = @"loading";
92
+ NSTimeInterval now = NSProcessInfo.processInfo.systemUptime;
93
+ if (!self.loadingSince) self.loadingSince = now;
94
+ if (now - self.loadingSince >= 30) [self fail:@"Audio loading or buffering timed out"];
95
+ } else {
96
+ self.loadingSince = 0;
97
+ self.state = self.wantsPlayback ? @"playing" : @"paused";
98
+ }
99
+ }
100
+
101
+ - (void)play {
102
+ [self refresh];
103
+ if (!self.player || self.disposed || [self.state isEqual:@"error"]) return;
104
+ if ([self.state isEqual:@"ended"]) {
105
+ [self.player seekToTime:kCMTimeZero];
106
+ self.state = @"paused";
107
+ }
108
+ self.wantsPlayback = YES;
109
+ [self.player play];
110
+ [self refresh];
111
+ }
112
+
113
+ - (void)pause {
114
+ if (!self.player || self.disposed) return;
115
+ self.wantsPlayback = NO;
116
+ [self.player pause];
117
+ [self refresh];
118
+ }
119
+
120
+ - (void)seekSeconds:(double)seconds {
121
+ if (!self.player || self.disposed || !isfinite(seconds)) return;
122
+ if ([self.state isEqual:@"ended"]) self.state = @"paused";
123
+ double duration = CMTimeGetSeconds(self.item.duration);
124
+ seconds = fmax(0, seconds);
125
+ if (isfinite(duration) && duration > 0) seconds = fmin(seconds, duration);
126
+ [self.player seekToTime:CMTimeMakeWithSeconds(seconds, 600) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
127
+ }
128
+
129
+ static double safeSeconds(CMTime time) {
130
+ double value = CMTimeGetSeconds(time);
131
+ return isfinite(value) && value > 0 ? value : 0;
132
+ }
133
+
134
+ - (NSString *)snapshot {
135
+ [self refresh];
136
+ NSMutableDictionary *value = [@{
137
+ @"state": self.state,
138
+ @"currentTime": @(self.player ? safeSeconds(self.player.currentTime) : 0),
139
+ @"duration": @(self.item ? safeSeconds(self.item.duration) : 0)
140
+ } mutableCopy];
141
+ if (self.failure) value[@"error"] = self.failure;
142
+ NSData *data = [NSJSONSerialization dataWithJSONObject:value options:0 error:nil];
143
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
144
+ }
145
+
146
+ - (void)clear {
147
+ [self releaseTrack];
148
+ self.failure = nil;
149
+ self.state = @"idle";
150
+ }
151
+
152
+ - (void)dispose {
153
+ if (self.disposed) return;
154
+ self.disposed = YES;
155
+ [self clear];
156
+ }
157
+
158
+ - (void)dealloc {
159
+ [self releaseTrack];
160
+ }
161
+ @end
@@ -1,5 +1,6 @@
1
1
  import { Utils } from '@nativescript/core'
2
2
  import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
3
+ import { android } from '@octane-xplat/platform/android'
3
4
 
4
5
  // The plugin's Java bridge is exposed by NativeScript's runtime metadata.
5
6
  declare const com: {
package/src/audio.ios.ts CHANGED
@@ -1,4 +1,20 @@
1
1
  import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
2
+ import {
3
+ AVAudioSession,
4
+ AVAudioSessionCategoryOptions,
5
+ AVAudioSessionSetActiveOptions,
6
+ AVPlayer,
7
+ AVPlayerItem,
8
+ MPNowPlayingInfoCenter,
9
+ MPRemoteCommandCenter,
10
+ NSDictionary,
11
+ NSMutableDictionary,
12
+ NSNotificationCenter,
13
+ NSOperationQueue,
14
+ NSURL,
15
+ } from '@octane-xplat/platform/ios'
16
+
17
+ import type { NSObjectProtocol } from '@octane-xplat/platform/ios'
2
18
 
3
19
  // CoreMedia is available at runtime but omitted from NativeScript's common
4
20
  // ambient references. Reuse AVPlayer's time type for this bridge slice.
@@ -11,7 +27,9 @@ export const createAudioPlayer = (): AudioPlayer => {
11
27
  const session = AVAudioSession.sharedInstance()
12
28
  // NativeScript's ambient const enums cannot be read with verbatimModuleSyntax.
13
29
  const interruptionBegan = 1 // AVAudioSessionInterruptionType.Began
30
+ const interruptionEnded = 0 // AVAudioSessionInterruptionType.Ended
14
31
  const interruptionShouldResume = 1 // AVAudioSessionInterruptionOptions.ShouldResume
32
+ const statusFailed = 2 // AVPlayerStatus.Failed
15
33
  const notifyOthersOnDeactivation = 1 as AVAudioSessionSetActiveOptions
16
34
  // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
17
35
  // needs MediaPlayer.framework linked AND metadata-generated — plugin
@@ -35,6 +53,7 @@ export const createAudioPlayer = (): AudioPlayer => {
35
53
  let wasPlayingBeforeInterruption = false
36
54
  let timer: ReturnType<typeof setInterval> | undefined
37
55
  let endObserver: NSObjectProtocol | undefined
56
+ let failureObserver: NSObjectProtocol | undefined
38
57
  let interruptionObserver: NSObjectProtocol | undefined
39
58
  const remoteTargets: Array<{ command: any; token: any }> = []
40
59
 
@@ -90,18 +109,31 @@ export const createAudioPlayer = (): AudioPlayer => {
90
109
  nowPlaying.nowPlayingInfo = info
91
110
  }
92
111
 
112
+ // AVPlayer failures arrive asynchronously — the item error carries the
113
+ // detail, falling back to the player error.
114
+ const playerError = () => {
115
+ const cause = player?.currentItem?.error ?? player?.error
116
+ return new Error(cause?.localizedDescription ?? 'Audio playback failed')
117
+ }
118
+
93
119
  const clearTrack = () => {
94
120
  if (endObserver) {
95
121
  NSNotificationCenter.defaultCenter.removeObserver(endObserver)
96
122
  endObserver = undefined
97
123
  }
98
124
 
125
+ if (failureObserver) {
126
+ NSNotificationCenter.defaultCenter.removeObserver(failureObserver)
127
+ failureObserver = undefined
128
+ }
129
+
99
130
  player?.pause()
100
131
  player = undefined
101
132
  }
102
133
 
103
134
  const load = async (autoplay = false) => {
104
135
  clearTrack()
136
+ wasPlayingBeforeInterruption = false
105
137
  const track = current()
106
138
  if (!track) {
107
139
  state = 'idle'
@@ -127,6 +159,22 @@ export const createAudioPlayer = (): AudioPlayer => {
127
159
  () => void advance(1),
128
160
  )
129
161
 
162
+ failureObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
163
+ AVPlayerItemFailedToPlayToEndTimeNotification,
164
+ item,
165
+ NSOperationQueue.mainQueue,
166
+ (notification) => {
167
+ const cause = notification.userInfo?.objectForKey(
168
+ AVPlayerItemFailedToPlayToEndTimeErrorKey,
169
+ )
170
+
171
+ error = new Error(cause?.localizedDescription ?? 'Audio playback failed')
172
+ state = 'error'
173
+ player?.pause()
174
+ emit()
175
+ },
176
+ )
177
+
130
178
  state = 'paused'
131
179
  updateNowPlaying()
132
180
  emit()
@@ -171,6 +219,12 @@ export const createAudioPlayer = (): AudioPlayer => {
171
219
  )
172
220
 
173
221
  session.setActiveWithOptionsError(true, 0 as AVAudioSessionSetActiveOptions, undefined)
222
+ if (state === 'ended') {
223
+ // The final item sits at end-of-stream — rewind before replaying,
224
+ // matching the macOS bridge's ended-restart.
225
+ player.seekToTime(CMTimeMakeWithSeconds(0, 600))
226
+ }
227
+
174
228
  player.play()
175
229
  state = 'playing'
176
230
  updateNowPlaying()
@@ -178,6 +232,9 @@ export const createAudioPlayer = (): AudioPlayer => {
178
232
  }
179
233
 
180
234
  const pause = async () => {
235
+ // An explicit pause must not be auto-resumed by a pending interruption
236
+ // Ended notification.
237
+ wasPlayingBeforeInterruption = false
181
238
  player?.pause()
182
239
  state = 'paused'
183
240
  updateNowPlaying()
@@ -221,7 +278,7 @@ export const createAudioPlayer = (): AudioPlayer => {
221
278
  player?.pause()
222
279
  state = 'paused'
223
280
  emit()
224
- } else if (wasPlayingBeforeInterruption) {
281
+ } else if (type === interruptionEnded && wasPlayingBeforeInterruption) {
225
282
  const options =
226
283
  notification.userInfo?.objectForKey(AVAudioSessionInterruptionOptionKey)
227
284
  ?.unsignedIntegerValue ?? 0
@@ -247,6 +304,14 @@ export const createAudioPlayer = (): AudioPlayer => {
247
304
  listeners.add(listener)
248
305
  listener(snapshot())
249
306
  timer ??= setInterval(() => {
307
+ if (
308
+ state !== 'error' &&
309
+ (player?.status === statusFailed || player?.currentItem?.status === statusFailed)
310
+ ) {
311
+ error = playerError()
312
+ state = 'error'
313
+ }
314
+
250
315
  updateNowPlaying()
251
316
  emit()
252
317
  }, 500)
@@ -0,0 +1,278 @@
1
+ import type { AudioPlayer, AudioSnapshot, Track } from './types'
2
+
3
+ type NativeSnapshot = Pick<AudioSnapshot, 'state' | 'currentTime' | 'duration'> & { error?: string }
4
+ type NativePlayer = {
5
+ setSource(source: string): void
6
+ play(): void
7
+ pause(): void
8
+ seekSeconds(seconds: number): void
9
+ snapshot(): string
10
+ clear(): void
11
+ dispose(): void
12
+ }
13
+
14
+ declare const XplatAudioPlayer: { new: () => NativePlayer }
15
+
16
+ /** The CLI loads the package's AVFoundation leaf before evaluating the app. */
17
+ export const createAudioPlayer = (): AudioPlayer => {
18
+ const native = typeof XplatAudioPlayer === 'undefined' ? undefined : XplatAudioPlayer.new()
19
+ const listeners = new Set<(snapshot: AudioSnapshot) => void>()
20
+ let queue: Track[] = []
21
+ let index = -1
22
+ let disposed = false
23
+ let generation = 0
24
+ let playRequest = 0
25
+ let timer: ReturnType<typeof setInterval> | undefined
26
+ let pending: { promise: Promise<void>; resolve(): void; reject(error: Error): void } | undefined
27
+ let value: AudioSnapshot = { state: 'idle', currentTime: 0, duration: 0 }
28
+
29
+ const assertActive = () => {
30
+ if (disposed) {
31
+ throw new Error('AudioPlayer is disposed')
32
+ }
33
+ }
34
+
35
+ const snapshot = () => ({ ...value, track: queue[index] ? { ...queue[index] } : undefined })
36
+ const emit = () => {
37
+ const currentGeneration = generation
38
+ const current = snapshot()
39
+ for (const listener of listeners) {
40
+ if (disposed || currentGeneration !== generation) {
41
+ break
42
+ }
43
+
44
+ listener(current)
45
+ }
46
+ }
47
+
48
+ const stopTimer = () => {
49
+ if (timer !== undefined) {
50
+ clearInterval(timer)
51
+ }
52
+
53
+ timer = undefined
54
+ }
55
+
56
+ const fail = (cause: unknown) => {
57
+ const error = cause instanceof Error ? cause : new Error(String(cause))
58
+ // Retain the original failure even when cleanup itself fails.
59
+ try {
60
+ native?.clear()
61
+ } catch {
62
+ /* The owned bridge has already failed. */
63
+ }
64
+
65
+ value = { ...value, state: 'error', error }
66
+ pending?.reject(error)
67
+ pending = undefined
68
+ stopTimer()
69
+ emit()
70
+ return error
71
+ }
72
+
73
+ const read = () => {
74
+ if (!native || disposed || value.state === 'error') {
75
+ return
76
+ }
77
+
78
+ const next = JSON.parse(native.snapshot()) as NativeSnapshot
79
+ if (next.state === 'error') {
80
+ throw new Error(next.error ?? 'Audio playback failed')
81
+ }
82
+
83
+ value = {
84
+ state: next.state,
85
+ currentTime: Number.isFinite(next.currentTime) ? Math.max(0, next.currentTime) : 0,
86
+ duration: Number.isFinite(next.duration) ? Math.max(0, next.duration) : 0,
87
+ }
88
+
89
+ if (pending && next.state !== 'loading') {
90
+ pending.resolve()
91
+ pending = undefined
92
+ }
93
+ }
94
+
95
+ const tick = () => {
96
+ if (disposed) {
97
+ return
98
+ }
99
+
100
+ try {
101
+ read()
102
+ } catch (cause) {
103
+ fail(cause)
104
+ return
105
+ }
106
+
107
+ if (value.state === 'ended') {
108
+ if (index + 1 < queue.length) {
109
+ index++
110
+ // Native notifications never own a rejected JS promise.
111
+ void load(true).catch(() => {})
112
+ return
113
+ }
114
+
115
+ stopTimer()
116
+ } else if (!pending && value.state !== 'playing' && value.state !== 'loading') {
117
+ // Paused/idle is stable — the poll only exists to observe loading
118
+ // resolution, playing progress, and the ended auto-advance.
119
+ stopTimer()
120
+ }
121
+
122
+ emit()
123
+ }
124
+
125
+ const load = async (autoplay = false) => {
126
+ const ownGeneration = ++generation
127
+ const ownPlayRequest = playRequest
128
+ pending?.reject(new Error('Audio load was superseded'))
129
+ pending = undefined
130
+ stopTimer()
131
+ value = { state: queue[index] ? 'loading' : 'idle', currentTime: 0, duration: 0 }
132
+ try {
133
+ native?.clear()
134
+ } catch (cause) {
135
+ throw fail(cause)
136
+ }
137
+
138
+ emit()
139
+ if (!queue[index] || disposed || ownGeneration !== generation) {
140
+ return
141
+ }
142
+
143
+ if (!native) {
144
+ throw fail(
145
+ new Error('macOS audio bridge is unavailable; rebuild the app with @octane-xplat/audio'),
146
+ )
147
+ }
148
+
149
+ let resolveReady!: () => void
150
+ let rejectReady!: (error: Error) => void
151
+ const ready = new Promise<void>((resolve, reject) => {
152
+ resolveReady = resolve
153
+ rejectReady = reject
154
+ })
155
+
156
+ pending = { promise: ready, resolve: resolveReady, reject: rejectReady }
157
+ // Attach before bridge calls, which may fail synchronously.
158
+ ready.catch(() => {})
159
+ try {
160
+ native.setSource(queue[index]!.source)
161
+ timer = setInterval(tick, 100)
162
+ tick()
163
+ } catch (cause) {
164
+ fail(cause)
165
+ }
166
+
167
+ await ready
168
+ if (autoplay && !disposed && ownGeneration === generation && ownPlayRequest === playRequest) {
169
+ await play()
170
+ }
171
+ }
172
+
173
+ const command = (action: (player: NativePlayer) => void) => {
174
+ assertActive()
175
+ if (value.error) {
176
+ throw value.error
177
+ }
178
+
179
+ if (!native || index < 0) {
180
+ return
181
+ }
182
+
183
+ try {
184
+ action(native)
185
+ read()
186
+ } catch (cause) {
187
+ throw fail(cause)
188
+ }
189
+
190
+ timer ??= setInterval(tick, 100)
191
+ emit()
192
+ }
193
+
194
+ const play = async () => {
195
+ assertActive()
196
+ const ownPlayRequest = ++playRequest
197
+ const ownGeneration = generation
198
+ await pending?.promise
199
+ assertActive()
200
+ if (ownGeneration !== generation) {
201
+ throw new Error('Audio load was superseded')
202
+ }
203
+
204
+ if (ownPlayRequest === playRequest) {
205
+ command((player) => player.play())
206
+ }
207
+ }
208
+
209
+ return {
210
+ capabilities: () => ({
211
+ supported: !!native,
212
+ backgroundPlayback: !!native,
213
+ systemControls: false,
214
+ userGestureRequired: false,
215
+ interruptions: false,
216
+ reason: native
217
+ ? undefined
218
+ : 'macOS audio bridge is unavailable; rebuild the app with @octane-xplat/audio',
219
+ }),
220
+ snapshot: () => {
221
+ try {
222
+ read()
223
+ } catch (cause) {
224
+ fail(cause)
225
+ }
226
+
227
+ return snapshot()
228
+ },
229
+ subscribe: (listener) => {
230
+ assertActive()
231
+ listeners.add(listener)
232
+ listener(snapshot())
233
+ return () => {
234
+ listeners.delete(listener)
235
+ }
236
+ },
237
+ setQueue: async (tracks, startAt = 0) => {
238
+ assertActive()
239
+ playRequest++
240
+ queue = tracks.map((track) => ({ ...track }))
241
+ index = queue.length
242
+ ? Math.max(
243
+ 0,
244
+ Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1),
245
+ )
246
+ : -1
247
+
248
+ await load()
249
+ },
250
+ play,
251
+ pause: async () => {
252
+ playRequest++
253
+ command((player) => player.pause())
254
+ },
255
+ seek: async (seconds) => {
256
+ assertActive()
257
+ if (Number.isFinite(seconds)) {
258
+ command((player) => player.seekSeconds(Math.max(0, seconds)))
259
+ }
260
+ },
261
+ dispose: () => {
262
+ if (disposed) {
263
+ return
264
+ }
265
+
266
+ disposed = true
267
+ generation++
268
+ pending?.reject(new Error('AudioPlayer is disposed'))
269
+ pending = undefined
270
+ stopTimer()
271
+ listeners.clear()
272
+ queue = []
273
+ index = -1
274
+ value = { state: 'idle', currentTime: 0, duration: 0 }
275
+ native?.dispose()
276
+ },
277
+ }
278
+ }
@@ -0,0 +1,2 @@
1
+ export type * from './types'
2
+ export { createAudioPlayer } from './audio.macos'
@@ -1,2 +0,0 @@
1
- import { createAudioPlayer } from "./index2.js";
2
- export { createAudioPlayer };
@@ -1,210 +0,0 @@
1
- //#region src/audio.ios.ts
2
- var createAudioPlayer = () => {
3
- const listeners = /* @__PURE__ */ new Set();
4
- const session = AVAudioSession.sharedInstance();
5
- const interruptionBegan = 1;
6
- const interruptionShouldResume = 1;
7
- const notifyOthersOnDeactivation = 1;
8
- const hasMediaPlayer = typeof MPRemoteCommandCenter !== "undefined" && typeof MPNowPlayingInfoCenter !== "undefined" && typeof globalThis.MPMediaItemPropertyPlaybackDuration !== "undefined" && typeof globalThis.MPRemoteCommandHandlerStatus !== "undefined";
9
- const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : void 0;
10
- const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : void 0;
11
- let queue = [];
12
- let index = -1;
13
- let player;
14
- let state = "idle";
15
- let error;
16
- let disposed = false;
17
- let wasPlayingBeforeInterruption = false;
18
- let timer;
19
- let endObserver;
20
- let interruptionObserver;
21
- const remoteTargets = [];
22
- const current = () => queue[index];
23
- const seconds = (time) => {
24
- const value = CMTimeGetSeconds(time);
25
- return Number.isFinite(value) && value > 0 ? value : 0;
26
- };
27
- const snapshot = () => ({
28
- state,
29
- track: current(),
30
- currentTime: player ? seconds(player.currentTime()) : 0,
31
- duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
32
- error
33
- });
34
- const emit = () => {
35
- const value = snapshot();
36
- for (const listener of listeners) listener(value);
37
- };
38
- const updateNowPlaying = () => {
39
- if (!nowPlaying) return;
40
- const track = current();
41
- if (!track) {
42
- nowPlaying.nowPlayingInfo = null;
43
- return;
44
- }
45
- const info = NSMutableDictionary.dictionary();
46
- info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle);
47
- if (track.artist) info.setObjectForKey(track.artist, MPMediaItemPropertyArtist);
48
- if (track.album) info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle);
49
- info.setObjectForKey(snapshot().duration, globalThis.MPMediaItemPropertyPlaybackDuration);
50
- info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime);
51
- info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate);
52
- nowPlaying.nowPlayingInfo = info;
53
- };
54
- const clearTrack = () => {
55
- if (endObserver) {
56
- NSNotificationCenter.defaultCenter.removeObserver(endObserver);
57
- endObserver = void 0;
58
- }
59
- player?.pause();
60
- player = void 0;
61
- };
62
- const load = async (autoplay = false) => {
63
- clearTrack();
64
- const track = current();
65
- if (!track) {
66
- state = "idle";
67
- updateNowPlaying();
68
- emit();
69
- return;
70
- }
71
- state = "loading";
72
- error = void 0;
73
- emit();
74
- try {
75
- const url = track.source.startsWith("/") ? NSURL.fileURLWithPath(track.source) : NSURL.URLWithString(track.source);
76
- const item = AVPlayerItem.playerItemWithURL(url);
77
- player = AVPlayer.playerWithPlayerItem(item);
78
- endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(AVPlayerItemDidPlayToEndTimeNotification, item, NSOperationQueue.mainQueue, () => void advance(1));
79
- state = "paused";
80
- updateNowPlaying();
81
- emit();
82
- if (autoplay) await play();
83
- } catch (cause) {
84
- error = cause instanceof Error ? cause : new Error(String(cause));
85
- state = "error";
86
- emit();
87
- throw error;
88
- }
89
- };
90
- const advance = async (delta) => {
91
- if (!queue.length || disposed) return;
92
- if (index + delta >= queue.length) {
93
- state = "ended";
94
- player?.pause();
95
- emit();
96
- return;
97
- }
98
- index = Math.max(0, index + delta);
99
- await load(true);
100
- };
101
- const play = async () => {
102
- if (!player || disposed) return;
103
- const category = AVAudioSessionCategoryPlayback;
104
- session.setCategoryModeOptionsError(category, AVAudioSessionModeDefault, 0, void 0);
105
- session.setActiveWithOptionsError(true, 0, void 0);
106
- player.play();
107
- state = "playing";
108
- updateNowPlaying();
109
- emit();
110
- };
111
- const pause = async () => {
112
- player?.pause();
113
- state = "paused";
114
- updateNowPlaying();
115
- emit();
116
- };
117
- const addRemoteTarget = (command, handler) => {
118
- const token = command.addTargetWithHandler((event) => {
119
- handler(event);
120
- return globalThis.MPRemoteCommandHandlerStatus.Success;
121
- });
122
- remoteTargets.push({
123
- command,
124
- token
125
- });
126
- };
127
- if (commandCenter) {
128
- addRemoteTarget(commandCenter.playCommand, () => void play());
129
- addRemoteTarget(commandCenter.pauseCommand, () => void pause());
130
- addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1));
131
- addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1));
132
- addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
133
- if (player && Number.isFinite(event.positionTime)) {
134
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600));
135
- updateNowPlaying();
136
- emit();
137
- }
138
- });
139
- }
140
- interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(AVAudioSessionInterruptionNotification, null, NSOperationQueue.mainQueue, (notification) => {
141
- if (notification.userInfo?.objectForKey(AVAudioSessionInterruptionTypeKey)?.unsignedIntegerValue === interruptionBegan) {
142
- wasPlayingBeforeInterruption = state === "playing";
143
- player?.pause();
144
- state = "paused";
145
- emit();
146
- } else if (wasPlayingBeforeInterruption) {
147
- const options = notification.userInfo?.objectForKey(AVAudioSessionInterruptionOptionKey)?.unsignedIntegerValue ?? 0;
148
- wasPlayingBeforeInterruption = false;
149
- if ((options & interruptionShouldResume) !== 0) play();
150
- }
151
- });
152
- return {
153
- capabilities: () => ({
154
- supported: true,
155
- backgroundPlayback: true,
156
- systemControls: hasMediaPlayer,
157
- userGestureRequired: false,
158
- interruptions: true
159
- }),
160
- snapshot,
161
- subscribe: (listener) => {
162
- listeners.add(listener);
163
- listener(snapshot());
164
- timer ??= setInterval(() => {
165
- updateNowPlaying();
166
- emit();
167
- }, 500);
168
- return () => {
169
- listeners.delete(listener);
170
- if (!listeners.size && timer) {
171
- clearInterval(timer);
172
- timer = void 0;
173
- }
174
- };
175
- },
176
- setQueue: async (tracks, startAt = 0) => {
177
- if (disposed) throw new Error("AudioPlayer is disposed");
178
- queue = [...tracks];
179
- index = queue.length ? Math.max(0, Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1)) : -1;
180
- await load();
181
- },
182
- play,
183
- pause,
184
- seek: async (value) => {
185
- if (!player || !Number.isFinite(value)) return;
186
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600));
187
- updateNowPlaying();
188
- emit();
189
- },
190
- dispose: () => {
191
- if (disposed) return;
192
- disposed = true;
193
- clearTrack();
194
- if (interruptionObserver) NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver);
195
- interruptionObserver = void 0;
196
- for (const { command, token } of remoteTargets) command.removeTarget(token);
197
- remoteTargets.length = 0;
198
- if (timer) clearInterval(timer);
199
- timer = void 0;
200
- if (nowPlaying) nowPlaying.nowPlayingInfo = null;
201
- session.setActiveWithOptionsError(false, notifyOthersOnDeactivation, null);
202
- listeners.clear();
203
- queue = [];
204
- index = -1;
205
- state = "idle";
206
- }
207
- };
208
- };
209
- //#endregion
210
- export { createAudioPlayer };
@@ -1,8 +0,0 @@
1
- {
2
- "version": 1,
3
- "buildId": "f2d28d65-9324-4ec9-bfce-6fe16e0caac3",
4
- "mode": "production",
5
- "capabilities": {
6
- "independentHydration": false
7
- }
8
- }
package/dist/web/index.js DELETED
@@ -1,2 +0,0 @@
1
- import { createAudioPlayer } from "./index2.js";
2
- export { createAudioPlayer };
@@ -1,147 +0,0 @@
1
- //#region src/audio.web.ts
2
- var createAudioPlayer = () => {
3
- const audio = new Audio();
4
- const listeners = /* @__PURE__ */ new Set();
5
- let queue = [];
6
- let index = -1;
7
- let state = "idle";
8
- let error;
9
- let disposed = false;
10
- const current = () => queue[index];
11
- const snapshot = () => ({
12
- state,
13
- track: current(),
14
- currentTime: audio.currentTime || 0,
15
- duration: Number.isFinite(audio.duration) ? audio.duration : 0,
16
- error
17
- });
18
- const emit = () => {
19
- const value = snapshot();
20
- for (const listener of listeners) listener(value);
21
- };
22
- const setTrack = () => {
23
- const track = current();
24
- if (!track) {
25
- audio.removeAttribute("src");
26
- state = "idle";
27
- emit();
28
- return;
29
- }
30
- audio.src = track.source;
31
- state = "loading";
32
- if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
33
- navigator.mediaSession.metadata = new MediaMetadata({
34
- title: track.title ?? track.id,
35
- artist: track.artist ?? "",
36
- album: track.album ?? ""
37
- });
38
- navigator.mediaSession.setActionHandler("play", () => {
39
- audio.play();
40
- });
41
- navigator.mediaSession.setActionHandler("pause", () => audio.pause());
42
- navigator.mediaSession.setActionHandler("seekto", (event) => {
43
- if (event.seekTime != null) audio.currentTime = event.seekTime;
44
- });
45
- navigator.mediaSession.setActionHandler("nexttrack", () => {
46
- advance(1);
47
- });
48
- navigator.mediaSession.setActionHandler("previoustrack", () => {
49
- advance(-1);
50
- });
51
- }
52
- emit();
53
- };
54
- const advance = async (delta) => {
55
- if (!queue.length) return;
56
- if (delta > 0 && index + 1 >= queue.length) {
57
- audio.pause();
58
- state = "ended";
59
- emit();
60
- return;
61
- }
62
- index = Math.max(0, Math.min(index + delta, queue.length - 1));
63
- setTrack();
64
- try {
65
- await audio.play();
66
- } catch (cause) {
67
- error = cause instanceof Error ? cause : new Error(String(cause));
68
- state = "error";
69
- emit();
70
- }
71
- };
72
- for (const event of [
73
- "timeupdate",
74
- "durationchange",
75
- "play",
76
- "playing",
77
- "pause",
78
- "ended",
79
- "waiting",
80
- "error"
81
- ]) audio.addEventListener(event, () => {
82
- if (event === "play") state = "loading";
83
- else if (event === "playing") state = "playing";
84
- else if (event === "pause" && state !== "ended") state = "paused";
85
- else if (event === "ended") {
86
- state = "ended";
87
- advance(1);
88
- return;
89
- } else if (event === "error") {
90
- state = "error";
91
- error = /* @__PURE__ */ new Error("Audio playback failed");
92
- } else if (event === "waiting") state = "loading";
93
- emit();
94
- });
95
- return {
96
- capabilities: () => ({
97
- supported: true,
98
- backgroundPlayback: false,
99
- systemControls: typeof navigator !== "undefined" && "mediaSession" in navigator,
100
- userGestureRequired: true,
101
- interruptions: false,
102
- reason: "Background playback and OS interruption handling are unavailable on web; autoplay may require a user gesture."
103
- }),
104
- snapshot,
105
- subscribe: (listener) => {
106
- listeners.add(listener);
107
- listener(snapshot());
108
- return () => listeners.delete(listener);
109
- },
110
- setQueue: async (tracks, startAt = 0) => {
111
- if (disposed) throw new Error("AudioPlayer is disposed");
112
- queue = [...tracks];
113
- index = queue.length ? Math.min(Math.max(Number.isFinite(startAt) ? Math.floor(startAt) : 0, 0), queue.length - 1) : -1;
114
- error = void 0;
115
- setTrack();
116
- },
117
- play: async () => {
118
- if (!disposed && current()) await audio.play();
119
- },
120
- pause: async () => {
121
- audio.pause();
122
- },
123
- seek: async (seconds) => {
124
- if (Number.isFinite(seconds)) audio.currentTime = Math.max(0, seconds);
125
- },
126
- dispose: () => {
127
- disposed = true;
128
- audio.pause();
129
- audio.removeAttribute("src");
130
- audio.load();
131
- listeners.clear();
132
- queue = [];
133
- if (typeof navigator !== "undefined" && "mediaSession" in navigator) {
134
- navigator.mediaSession.metadata = null;
135
- for (const action of [
136
- "play",
137
- "pause",
138
- "seekto",
139
- "nexttrack",
140
- "previoustrack"
141
- ]) navigator.mediaSession.setActionHandler(action, null);
142
- }
143
- }
144
- };
145
- };
146
- //#endregion
147
- export { createAudioPlayer };
@@ -1,8 +0,0 @@
1
- {
2
- "version": 1,
3
- "buildId": "f383285e-9461-4235-9669-86a3e0189e28",
4
- "mode": "production",
5
- "capabilities": {
6
- "independentHydration": false
7
- }
8
- }