@octane-xplat/audio 0.19.0 → 0.20.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/src/audio.ios.ts CHANGED
@@ -2,18 +2,18 @@ import { copyQueue } from './queue'
2
2
  import { bounded } from './settings'
3
3
  import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
4
4
  import {
5
- AVAudioSession,
6
- AVAudioSessionCategoryOptions,
7
- AVAudioSessionSetActiveOptions,
8
- AVPlayer,
9
- AVPlayerItem,
10
- MPNowPlayingInfoCenter,
11
- MPRemoteCommandCenter,
12
- NSDictionary,
13
- NSMutableDictionary,
14
- NSNotificationCenter,
15
- NSOperationQueue,
16
- NSURL,
5
+ AVAudioSession,
6
+ AVAudioSessionCategoryOptions,
7
+ AVAudioSessionSetActiveOptions,
8
+ AVPlayer,
9
+ AVPlayerItem,
10
+ MPNowPlayingInfoCenter,
11
+ MPRemoteCommandCenter,
12
+ NSDictionary,
13
+ NSMutableDictionary,
14
+ NSNotificationCenter,
15
+ NSOperationQueue,
16
+ NSURL,
17
17
  } from '@octane-xplat/platform/ios'
18
18
 
19
19
  import type { NSObjectProtocol } from '@octane-xplat/platform/ios'
@@ -26,464 +26,484 @@ declare function CMTimeMakeWithSeconds(seconds: number, preferredTimescale: numb
26
26
 
27
27
  /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
28
28
  export const createAudioPlayer = (): AudioPlayer => {
29
- const listeners = new Set<(snapshot: AudioSnapshot) => void>()
30
- const session = AVAudioSession.sharedInstance()
31
- // NativeScript's ambient const enums cannot be read with verbatimModuleSyntax.
32
- const interruptionBegan = 1 // AVAudioSessionInterruptionType.Began
33
- const interruptionEnded = 0 // AVAudioSessionInterruptionType.Ended
34
- const interruptionShouldResume = 1 // AVAudioSessionInterruptionOptions.ShouldResume
35
- const statusFailed = 2 // AVPlayerStatus.Failed
36
- const notifyOthersOnDeactivation = 1 as AVAudioSessionSetActiveOptions
37
- // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
38
- // needs MediaPlayer.framework linked AND metadata-generated — plugin
39
- // LDFLAGS alone don't reach the metadata scan, so the MP* globals can be
40
- // undefined. Playback still works; guard and report systemControls:false.
41
- const hasMediaPlayer =
42
- typeof MPRemoteCommandCenter !== 'undefined' &&
43
- typeof MPNowPlayingInfoCenter !== 'undefined' &&
44
- // The runtime metadata keys may be absent when MediaPlayer isn't linked.
45
- typeof (globalThis as any).MPMediaItemPropertyPlaybackDuration !== 'undefined' &&
46
- typeof (globalThis as any).MPRemoteCommandHandlerStatus !== 'undefined'
47
-
48
- const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : undefined
49
- const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : undefined
50
- let queue: Track[] = []
51
- let index = -1
52
- let player: AVPlayer | undefined
53
- let state: AudioSnapshot['state'] = 'idle'
54
- let error: Error | undefined
55
- let disposed = false
56
- let generation = 0
57
- let playbackRate = 1
58
- let volume = 1
59
- let muted = false
60
- let queueComplete = true
61
- let waitingToResume = false
62
- let wasPlayingBeforeInterruption = false
63
- let timer: ReturnType<typeof setInterval> | undefined
64
- let endObserver: NSObjectProtocol | undefined
65
- let failureObserver: NSObjectProtocol | undefined
66
- let interruptionObserver: NSObjectProtocol | undefined
67
- const remoteTargets: Array<{ command: any; token: any }> = []
68
-
69
- const current = () => queue[index]
70
- const seconds = (time: PlayerTime) => {
71
- const value = CMTimeGetSeconds(time)
72
- return Number.isFinite(value) && value > 0 ? value : 0
73
- }
74
-
75
- const snapshot = (): AudioSnapshot => ({
76
- state,
77
- playbackRate,
78
- volume,
79
- muted,
80
- queueComplete,
81
- track: current(),
82
- currentTime: player ? seconds(player.currentTime()) : 0,
83
- duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
84
- error,
85
- })
86
-
87
- const emit = () => {
88
- const value = snapshot()
89
- const ownGeneration = generation
90
- for (const listener of listeners) {
91
- if (disposed || ownGeneration !== generation) {
92
- break
93
- }
94
-
95
- listener(value)
96
- }
97
- }
98
-
99
- const updateNowPlaying = () => {
100
- if (!nowPlaying) {
101
- return
102
- }
103
-
104
- const track = current()
105
- if (!track) {
106
- nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
107
- return
108
- }
109
-
110
- const info = NSMutableDictionary.dictionary()
111
- info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle)
112
- if (track.artist) {
113
- info.setObjectForKey(track.artist, MPMediaItemPropertyArtist)
114
- }
115
-
116
- if (track.album) {
117
- info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle)
118
- }
119
-
120
- info.setObjectForKey(
121
- snapshot().duration,
122
- (globalThis as any).MPMediaItemPropertyPlaybackDuration,
123
- )
124
-
125
- info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime)
126
- info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate)
127
- nowPlaying.nowPlayingInfo = info
128
- }
129
-
130
- // AVPlayer failures arrive asynchronously — the item error carries the
131
- // detail, falling back to the player error.
132
- const playerError = () => {
133
- const cause = player?.currentItem?.error ?? player?.error
134
- return new Error(cause?.localizedDescription ?? 'Audio playback failed')
135
- }
136
-
137
- const clearTrack = () => {
138
- if (endObserver) {
139
- NSNotificationCenter.defaultCenter.removeObserver(endObserver)
140
- endObserver = undefined
141
- }
142
-
143
- if (failureObserver) {
144
- NSNotificationCenter.defaultCenter.removeObserver(failureObserver)
145
- failureObserver = undefined
146
- }
147
-
148
- player?.pause()
149
- player = undefined
150
- }
151
-
152
- const load = async (autoplay = false) => {
153
- const ownGeneration = ++generation
154
- clearTrack()
155
- wasPlayingBeforeInterruption = false
156
- const track = current()
157
- if (!track) {
158
- state = 'idle'
159
- updateNowPlaying()
160
- emit()
161
- return
162
- }
163
-
164
- state = 'loading'
165
- error = undefined
166
- emit()
167
- if (disposed || ownGeneration !== generation) {
168
- return
169
- }
170
- try {
171
- const url = track.source.startsWith('/')
172
- ? NSURL.fileURLWithPath(track.source)
173
- : NSURL.URLWithString(track.source)
174
-
175
- const item = AVPlayerItem.playerItemWithURL(url)
176
- item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmTimeDomain
177
- player = AVPlayer.playerWithPlayerItem(item)
178
- player.volume = volume
179
- player.muted = muted
180
- endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
181
- AVPlayerItemDidPlayToEndTimeNotification,
182
- item,
183
- NSOperationQueue.mainQueue,
184
- () => {
185
- if (!disposed && ownGeneration === generation) {
186
- void advance(1).catch(() => {})
187
- }
188
- },
189
- )
190
-
191
- failureObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
192
- AVPlayerItemFailedToPlayToEndTimeNotification,
193
- item,
194
- NSOperationQueue.mainQueue,
195
- (notification) => {
196
- if (disposed || ownGeneration !== generation) {
197
- return
198
- }
199
- const cause = notification.userInfo?.objectForKey(
200
- AVPlayerItemFailedToPlayToEndTimeErrorKey,
201
- )
202
-
203
- error = new Error(cause?.localizedDescription ?? 'Audio playback failed')
204
- state = 'error'
205
- player?.pause()
206
- emit()
207
- },
208
- )
209
-
210
- state = 'paused'
211
- updateNowPlaying()
212
- emit()
213
- if (autoplay) {
214
- await play()
215
- }
216
- } catch (cause) {
217
- error = cause instanceof Error ? cause : new Error(String(cause))
218
- state = 'error'
219
- emit()
220
- throw error
221
- }
222
- }
223
-
224
- const advance = async (delta: number) => {
225
- if (!queue.length || disposed) {
226
- return
227
- }
228
-
229
- if (index + delta >= queue.length) {
230
- state = queueComplete ? 'ended' : 'waiting'
231
- waitingToResume = !queueComplete
232
- player?.pause()
233
- emit()
234
- return
235
- }
236
-
237
- index = Math.max(0, index + delta)
238
- await load(true)
239
- }
240
-
241
- const play = async () => {
242
- if (!player || disposed) {
243
- return
244
- }
245
-
246
- const category = AVAudioSessionCategoryPlayback
247
- session.setCategoryModeOptionsError(
248
- category,
249
- AVAudioSessionModeDefault,
250
- 0 as AVAudioSessionCategoryOptions,
251
- undefined,
252
- )
253
-
254
- session.setActiveWithOptionsError(true, 0 as AVAudioSessionSetActiveOptions, undefined)
255
- if (state === 'ended') {
256
- // The final item sits at end-of-stream — rewind before replaying,
257
- // matching the macOS bridge's ended-restart.
258
- player.seekToTime(CMTimeMakeWithSeconds(0, 600))
259
- }
260
-
261
- player.play()
262
- player.rate = playbackRate
263
- state = 'playing'
264
- updateNowPlaying()
265
- emit()
266
- }
267
-
268
- const pause = async () => {
269
- // An explicit pause must not be auto-resumed by a pending interruption
270
- // Ended notification.
271
- wasPlayingBeforeInterruption = false
272
- waitingToResume = false
273
- player?.pause()
274
- state = 'paused'
275
- updateNowPlaying()
276
- emit()
277
- }
278
-
279
- const addRemoteTarget = (command: any, handler: (event?: any) => void) => {
280
- const token = command.addTargetWithHandler((event: any) => {
281
- handler(event)
282
- return (globalThis as any).MPRemoteCommandHandlerStatus.Success
283
- })
284
-
285
- remoteTargets.push({ command, token })
286
- }
287
-
288
- if (commandCenter) {
289
- addRemoteTarget(commandCenter.playCommand, () => void play())
290
- addRemoteTarget(commandCenter.pauseCommand, () => void pause())
291
- addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1))
292
- addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1))
293
- addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
294
- if (player && Number.isFinite(event.positionTime)) {
295
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600))
296
- updateNowPlaying()
297
- emit()
298
- }
299
- })
300
- }
301
-
302
- interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
303
- AVAudioSessionInterruptionNotification,
304
- null,
305
- NSOperationQueue.mainQueue,
306
- (notification) => {
307
- const type = notification.userInfo?.objectForKey(
308
- AVAudioSessionInterruptionTypeKey,
309
- )?.unsignedIntegerValue
310
-
311
- if (type === interruptionBegan) {
312
- wasPlayingBeforeInterruption = state === 'playing'
313
- player?.pause()
314
- state = 'paused'
315
- emit()
316
- } else if (type === interruptionEnded && wasPlayingBeforeInterruption) {
317
- const options =
318
- notification.userInfo?.objectForKey(AVAudioSessionInterruptionOptionKey)
319
- ?.unsignedIntegerValue ?? 0
320
-
321
- wasPlayingBeforeInterruption = false
322
- if ((options & interruptionShouldResume) !== 0) {
323
- void play()
324
- }
325
- }
326
- },
327
- )
328
-
329
- return {
330
- capabilities: (): AudioCapabilities => ({
331
- supported: true,
332
- backgroundPlayback: true,
333
- systemControls: hasMediaPlayer,
334
- userGestureRequired: false,
335
- interruptions: true,
336
- }),
337
- snapshot,
338
- subscribe: (listener) => {
339
- listeners.add(listener)
340
- listener(snapshot())
341
- timer ??= setInterval(() => {
342
- if (
343
- state !== 'error' &&
344
- (player?.status === statusFailed || player?.currentItem?.status === statusFailed)
345
- ) {
346
- error = playerError()
347
- state = 'error'
348
- }
349
-
350
- updateNowPlaying()
351
- emit()
352
- }, 500)
353
-
354
- return () => {
355
- listeners.delete(listener)
356
- if (!listeners.size && timer) {
357
- clearInterval(timer)
358
- timer = undefined
359
- }
360
- }
361
- },
362
- setQueue: async (tracks, startAt = 0, options = {}) => {
363
- if (disposed) {
364
- throw new Error('AudioPlayer is disposed')
365
- }
366
-
367
- queue = copyQueue(tracks)
368
- queueComplete = options.complete ?? true
369
- waitingToResume = false
370
- index = queue.length
371
- ? Math.max(
372
- 0,
373
- Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1),
374
- )
375
- : -1
376
-
377
- await load()
378
- },
379
- play,
380
- pause,
381
- seek: async (value) => {
382
- if (!player || !Number.isFinite(value)) {
383
- return
384
- }
385
-
386
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600))
387
- updateNowPlaying()
388
- emit()
389
- },
390
-
391
- updateQueue: async (tracks, options = {}) => {
392
- if (disposed) {
393
- throw new Error('AudioPlayer is disposed')
394
- }
395
- const next = copyQueue(tracks)
396
- const old = current()
397
- const at = old ? next.findIndex((t) => t.id === old.id && t.source === old.source) : -1
398
- queue = next
399
- queueComplete = options.complete ?? queueComplete
400
- if (at < 0) {
401
- waitingToResume = false
402
- index = next.length ? 0 : -1
403
-
404
- await load()
405
- } else {
406
- index = at
407
- if (state === 'waiting' && waitingToResume && index + 1 < queue.length) {
408
- waitingToResume = false
409
- await advance(1)
410
- } else if (state === 'waiting' && queueComplete) {
411
- state = 'ended'
412
- waitingToResume = false
413
- }
414
-
415
- updateNowPlaying()
416
- emit()
417
- }
418
- },
419
- setPlaybackRate: async (rate) => {
420
- if (disposed) {
421
- throw new Error('AudioPlayer is disposed')
422
- }
423
- playbackRate = bounded(rate, 0.5, 3)
424
- if (player && state === 'playing') {
425
- player.rate = playbackRate
426
- }
427
- updateNowPlaying()
428
- emit()
429
- },
430
- setVolume: async (gain) => {
431
- if (disposed) {
432
- throw new Error('AudioPlayer is disposed')
433
- }
434
- volume = bounded(gain, 0, 1)
435
- if (player) {
436
- player.volume = volume
437
- }
438
- emit()
439
- },
440
- setMuted: async (value) => {
441
- if (disposed) {
442
- throw new Error('AudioPlayer is disposed')
443
- }
444
- muted = value
445
- if (player) {
446
- player.muted = muted
447
- }
448
- emit()
449
- },
450
- dispose: () => {
451
- if (disposed) {
452
- return
453
- }
454
-
455
- disposed = true
456
- generation++
457
- clearTrack()
458
- if (interruptionObserver) {
459
- NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver)
460
- }
461
-
462
- interruptionObserver = undefined
463
- for (const { command, token } of remoteTargets) {
464
- command.removeTarget(token)
465
- }
466
-
467
- remoteTargets.length = 0
468
- if (timer) {
469
- clearInterval(timer)
470
- }
471
-
472
- timer = undefined
473
- if (nowPlaying) {
474
- nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
475
- }
476
-
477
- // The Objective-C error-out argument is intentionally null at runtime;
478
- // NativeScript's generated type only permits Reference<NSError> | undefined.
479
- const noErrorOut = null as unknown as Parameters<typeof session.setActiveWithOptionsError>[2]
480
-
481
- session.setActiveWithOptionsError(false, notifyOthersOnDeactivation, noErrorOut)
482
-
483
- listeners.clear()
484
- queue = []
485
- index = -1
486
- state = 'idle'
487
- },
488
- }
29
+ const listeners = new Set<(snapshot: AudioSnapshot) => void>()
30
+ const session = AVAudioSession.sharedInstance()
31
+ // NativeScript's ambient const enums cannot be read with verbatimModuleSyntax.
32
+ const interruptionBegan = 1 // AVAudioSessionInterruptionType.Began
33
+ const interruptionEnded = 0 // AVAudioSessionInterruptionType.Ended
34
+ const interruptionShouldResume = 1 // AVAudioSessionInterruptionOptions.ShouldResume
35
+ const statusFailed = 2 // AVPlayerStatus.Failed
36
+ const notifyOthersOnDeactivation = 1 as AVAudioSessionSetActiveOptions
37
+ // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
38
+ // needs MediaPlayer.framework linked AND metadata-generated — plugin
39
+ // LDFLAGS alone don't reach the metadata scan, so the MP* globals can be
40
+ // undefined. Playback still works; guard and report systemControls:false.
41
+ const hasMediaPlayer =
42
+ typeof MPRemoteCommandCenter !== 'undefined' &&
43
+ typeof MPNowPlayingInfoCenter !== 'undefined' &&
44
+ // The runtime metadata keys may be absent when MediaPlayer isn't linked.
45
+ typeof (globalThis as any).MPMediaItemPropertyPlaybackDuration !== 'undefined' &&
46
+ typeof (globalThis as any).MPRemoteCommandHandlerStatus !== 'undefined'
47
+
48
+ const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : undefined
49
+ const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : undefined
50
+ let queue: Track[] = []
51
+ let index = -1
52
+ let player: AVPlayer | undefined
53
+ let state: AudioSnapshot['state'] = 'idle'
54
+ let error: Error | undefined
55
+ let disposed = false
56
+ let generation = 0
57
+ let playbackRate = 1
58
+ let volume = 1
59
+ let muted = false
60
+ let queueComplete = true
61
+ let waitingToResume = false
62
+ let wasPlayingBeforeInterruption = false
63
+ let timer: ReturnType<typeof setInterval> | undefined
64
+ let endObserver: NSObjectProtocol | undefined
65
+ let failureObserver: NSObjectProtocol | undefined
66
+ let interruptionObserver: NSObjectProtocol | undefined
67
+ const remoteTargets: Array<{ command: any; token: any }> = []
68
+
69
+ const current = () => queue[index]
70
+ const seconds = (time: PlayerTime) => {
71
+ const value = CMTimeGetSeconds(time)
72
+
73
+ return Number.isFinite(value) && value > 0 ? value : 0
74
+ }
75
+
76
+ const snapshot = (): AudioSnapshot => ({
77
+ state,
78
+ playbackRate,
79
+ volume,
80
+ muted,
81
+ queueComplete,
82
+ track: current(),
83
+ currentTime: player ? seconds(player.currentTime()) : 0,
84
+ duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
85
+ error,
86
+ })
87
+
88
+ const emit = () => {
89
+ const value = snapshot()
90
+ const ownGeneration = generation
91
+
92
+ for (const listener of listeners) {
93
+ if (disposed || ownGeneration !== generation) {
94
+ break
95
+ }
96
+
97
+ listener(value)
98
+ }
99
+ }
100
+
101
+ const updateNowPlaying = () => {
102
+ if (!nowPlaying) {
103
+ return
104
+ }
105
+
106
+ const track = current()
107
+
108
+ if (!track) {
109
+ nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
110
+ return
111
+ }
112
+
113
+ const info = NSMutableDictionary.dictionary()
114
+
115
+ info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle)
116
+ if (track.artist) {
117
+ info.setObjectForKey(track.artist, MPMediaItemPropertyArtist)
118
+ }
119
+
120
+ if (track.album) {
121
+ info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle)
122
+ }
123
+
124
+ info.setObjectForKey(
125
+ snapshot().duration,
126
+ (globalThis as any).MPMediaItemPropertyPlaybackDuration,
127
+ )
128
+
129
+ info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime)
130
+ info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate)
131
+ nowPlaying.nowPlayingInfo = info
132
+ }
133
+
134
+ // AVPlayer failures arrive asynchronously — the item error carries the
135
+ // detail, falling back to the player error.
136
+ const playerError = () => {
137
+ const cause = player?.currentItem?.error ?? player?.error
138
+
139
+ return new Error(cause?.localizedDescription ?? 'Audio playback failed')
140
+ }
141
+
142
+ const clearTrack = () => {
143
+ if (endObserver) {
144
+ NSNotificationCenter.defaultCenter.removeObserver(endObserver)
145
+ endObserver = undefined
146
+ }
147
+
148
+ if (failureObserver) {
149
+ NSNotificationCenter.defaultCenter.removeObserver(failureObserver)
150
+ failureObserver = undefined
151
+ }
152
+
153
+ player?.pause()
154
+ player = undefined
155
+ }
156
+
157
+ const load = async (autoplay = false) => {
158
+ const ownGeneration = ++generation
159
+
160
+ clearTrack()
161
+ wasPlayingBeforeInterruption = false
162
+
163
+ const track = current()
164
+
165
+ if (!track) {
166
+ state = 'idle'
167
+ updateNowPlaying()
168
+ emit()
169
+ return
170
+ }
171
+
172
+ state = 'loading'
173
+ error = undefined
174
+ emit()
175
+ if (disposed || ownGeneration !== generation) {
176
+ return
177
+ }
178
+
179
+ try {
180
+ const url = track.source.startsWith('/')
181
+ ? NSURL.fileURLWithPath(track.source)
182
+ : NSURL.URLWithString(track.source)
183
+
184
+ const item = AVPlayerItem.playerItemWithURL(url)
185
+
186
+ item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmTimeDomain
187
+ player = AVPlayer.playerWithPlayerItem(item)
188
+ player.volume = volume
189
+ player.muted = muted
190
+ endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
191
+ AVPlayerItemDidPlayToEndTimeNotification,
192
+ item,
193
+ NSOperationQueue.mainQueue,
194
+ () => {
195
+ if (!disposed && ownGeneration === generation) {
196
+ void advance(1).catch(() => {})
197
+ }
198
+ },
199
+ )
200
+
201
+ failureObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
202
+ AVPlayerItemFailedToPlayToEndTimeNotification,
203
+ item,
204
+ NSOperationQueue.mainQueue,
205
+ (notification) => {
206
+ if (disposed || ownGeneration !== generation) {
207
+ return
208
+ }
209
+
210
+ const cause = notification.userInfo?.objectForKey(
211
+ AVPlayerItemFailedToPlayToEndTimeErrorKey,
212
+ )
213
+
214
+ error = new Error(cause?.localizedDescription ?? 'Audio playback failed')
215
+ state = 'error'
216
+ player?.pause()
217
+ emit()
218
+ },
219
+ )
220
+
221
+ state = 'paused'
222
+ updateNowPlaying()
223
+ emit()
224
+ if (autoplay) {
225
+ await play()
226
+ }
227
+ } catch (cause) {
228
+ error = cause instanceof Error ? cause : new Error(String(cause))
229
+ state = 'error'
230
+ emit()
231
+ throw error
232
+ }
233
+ }
234
+
235
+ const advance = async (delta: number) => {
236
+ if (!queue.length || disposed) {
237
+ return
238
+ }
239
+
240
+ if (index + delta >= queue.length) {
241
+ state = queueComplete ? 'ended' : 'waiting'
242
+ waitingToResume = !queueComplete
243
+ player?.pause()
244
+ emit()
245
+ return
246
+ }
247
+
248
+ index = Math.max(0, index + delta)
249
+ await load(true)
250
+ }
251
+
252
+ const play = async () => {
253
+ if (!player || disposed) {
254
+ return
255
+ }
256
+
257
+ const category = AVAudioSessionCategoryPlayback
258
+
259
+ session.setCategoryModeOptionsError(
260
+ category,
261
+ AVAudioSessionModeDefault,
262
+ 0 as AVAudioSessionCategoryOptions,
263
+ undefined,
264
+ )
265
+
266
+ session.setActiveWithOptionsError(true, 0 as AVAudioSessionSetActiveOptions, undefined)
267
+ if (state === 'ended') {
268
+ // The final item sits at end-of-stream — rewind before replaying,
269
+ // matching the macOS bridge's ended-restart.
270
+ player.seekToTime(CMTimeMakeWithSeconds(0, 600))
271
+ }
272
+
273
+ player.play()
274
+ player.rate = playbackRate
275
+ state = 'playing'
276
+ updateNowPlaying()
277
+ emit()
278
+ }
279
+
280
+ const pause = async () => {
281
+ // An explicit pause must not be auto-resumed by a pending interruption
282
+ // Ended notification.
283
+ wasPlayingBeforeInterruption = false
284
+ waitingToResume = false
285
+ player?.pause()
286
+ state = 'paused'
287
+ updateNowPlaying()
288
+ emit()
289
+ }
290
+
291
+ const addRemoteTarget = (command: any, handler: (event?: any) => void) => {
292
+ const token = command.addTargetWithHandler((event: any) => {
293
+ handler(event)
294
+ return (globalThis as any).MPRemoteCommandHandlerStatus.Success
295
+ })
296
+
297
+ remoteTargets.push({ command, token })
298
+ }
299
+
300
+ if (commandCenter) {
301
+ addRemoteTarget(commandCenter.playCommand, () => void play())
302
+ addRemoteTarget(commandCenter.pauseCommand, () => void pause())
303
+ addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1))
304
+ addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1))
305
+ addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
306
+ if (player && Number.isFinite(event.positionTime)) {
307
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600))
308
+ updateNowPlaying()
309
+ emit()
310
+ }
311
+ })
312
+ }
313
+
314
+ interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
315
+ AVAudioSessionInterruptionNotification,
316
+ null,
317
+ NSOperationQueue.mainQueue,
318
+ (notification) => {
319
+ const type = notification.userInfo?.objectForKey(
320
+ AVAudioSessionInterruptionTypeKey,
321
+ )?.unsignedIntegerValue
322
+
323
+ if (type === interruptionBegan) {
324
+ wasPlayingBeforeInterruption = state === 'playing'
325
+ player?.pause()
326
+ state = 'paused'
327
+ emit()
328
+ } else if (type === interruptionEnded && wasPlayingBeforeInterruption) {
329
+ const options =
330
+ notification.userInfo?.objectForKey(AVAudioSessionInterruptionOptionKey)
331
+ ?.unsignedIntegerValue ?? 0
332
+
333
+ wasPlayingBeforeInterruption = false
334
+ if ((options & interruptionShouldResume) !== 0) {
335
+ void play()
336
+ }
337
+ }
338
+ },
339
+ )
340
+
341
+ return {
342
+ capabilities: (): AudioCapabilities => ({
343
+ supported: true,
344
+ backgroundPlayback: true,
345
+ systemControls: hasMediaPlayer,
346
+ userGestureRequired: false,
347
+ interruptions: true,
348
+ }),
349
+ snapshot,
350
+ subscribe: (listener) => {
351
+ listeners.add(listener)
352
+ listener(snapshot())
353
+ timer ??= setInterval(() => {
354
+ if (
355
+ state !== 'error' &&
356
+ (player?.status === statusFailed || player?.currentItem?.status === statusFailed)
357
+ ) {
358
+ error = playerError()
359
+ state = 'error'
360
+ }
361
+
362
+ updateNowPlaying()
363
+ emit()
364
+ }, 500)
365
+
366
+ return () => {
367
+ listeners.delete(listener)
368
+ if (!listeners.size && timer) {
369
+ clearInterval(timer)
370
+ timer = undefined
371
+ }
372
+ }
373
+ },
374
+ setQueue: async (tracks, startAt = 0, options = {}) => {
375
+ if (disposed) {
376
+ throw new Error('AudioPlayer is disposed')
377
+ }
378
+
379
+ queue = copyQueue(tracks)
380
+ queueComplete = options.complete ?? true
381
+ waitingToResume = false
382
+ index = queue.length
383
+ ? Math.max(
384
+ 0,
385
+ Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1),
386
+ )
387
+ : -1
388
+
389
+ await load()
390
+ },
391
+ play,
392
+ pause,
393
+ seek: async (value) => {
394
+ if (!player || !Number.isFinite(value)) {
395
+ return
396
+ }
397
+
398
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600))
399
+ updateNowPlaying()
400
+ emit()
401
+ },
402
+
403
+ updateQueue: async (tracks, options = {}) => {
404
+ if (disposed) {
405
+ throw new Error('AudioPlayer is disposed')
406
+ }
407
+
408
+ const next = copyQueue(tracks)
409
+ const old = current()
410
+ const at = old ? next.findIndex((t) => t.id === old.id && t.source === old.source) : -1
411
+
412
+ queue = next
413
+ queueComplete = options.complete ?? queueComplete
414
+ if (at < 0) {
415
+ waitingToResume = false
416
+ index = next.length ? 0 : -1
417
+
418
+ await load()
419
+ } else {
420
+ index = at
421
+ if (state === 'waiting' && waitingToResume && index + 1 < queue.length) {
422
+ waitingToResume = false
423
+ await advance(1)
424
+ } else if (state === 'waiting' && queueComplete) {
425
+ state = 'ended'
426
+ waitingToResume = false
427
+ }
428
+
429
+ updateNowPlaying()
430
+ emit()
431
+ }
432
+ },
433
+ setPlaybackRate: async (rate) => {
434
+ if (disposed) {
435
+ throw new Error('AudioPlayer is disposed')
436
+ }
437
+
438
+ playbackRate = bounded(rate, 0.5, 3)
439
+ if (player && state === 'playing') {
440
+ player.rate = playbackRate
441
+ }
442
+
443
+ updateNowPlaying()
444
+ emit()
445
+ },
446
+ setVolume: async (gain) => {
447
+ if (disposed) {
448
+ throw new Error('AudioPlayer is disposed')
449
+ }
450
+
451
+ volume = bounded(gain, 0, 1)
452
+ if (player) {
453
+ player.volume = volume
454
+ }
455
+
456
+ emit()
457
+ },
458
+ setMuted: async (value) => {
459
+ if (disposed) {
460
+ throw new Error('AudioPlayer is disposed')
461
+ }
462
+
463
+ muted = value
464
+ if (player) {
465
+ player.muted = muted
466
+ }
467
+
468
+ emit()
469
+ },
470
+ dispose: () => {
471
+ if (disposed) {
472
+ return
473
+ }
474
+
475
+ disposed = true
476
+ generation++
477
+ clearTrack()
478
+ if (interruptionObserver) {
479
+ NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver)
480
+ }
481
+
482
+ interruptionObserver = undefined
483
+ for (const { command, token } of remoteTargets) {
484
+ command.removeTarget(token)
485
+ }
486
+
487
+ remoteTargets.length = 0
488
+ if (timer) {
489
+ clearInterval(timer)
490
+ }
491
+
492
+ timer = undefined
493
+ if (nowPlaying) {
494
+ nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
495
+ }
496
+
497
+ // The Objective-C error-out argument is intentionally null at runtime;
498
+ // NativeScript's generated type only permits Reference<NSError> | undefined.
499
+ const noErrorOut = null as unknown as Parameters<typeof session.setActiveWithOptionsError>[2]
500
+
501
+ session.setActiveWithOptionsError(false, notifyOthersOnDeactivation, noErrorOut)
502
+
503
+ listeners.clear()
504
+ queue = []
505
+ index = -1
506
+ state = 'idle'
507
+ },
508
+ }
489
509
  }