@octane-xplat/audio 0.18.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
@@ -1,17 +1,19 @@
1
+ import { copyQueue } from './queue'
2
+ import { bounded } from './settings'
1
3
  import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
2
4
  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,
5
+ AVAudioSession,
6
+ AVAudioSessionCategoryOptions,
7
+ AVAudioSessionSetActiveOptions,
8
+ AVPlayer,
9
+ AVPlayerItem,
10
+ MPNowPlayingInfoCenter,
11
+ MPRemoteCommandCenter,
12
+ NSDictionary,
13
+ NSMutableDictionary,
14
+ NSNotificationCenter,
15
+ NSOperationQueue,
16
+ NSURL,
15
17
  } from '@octane-xplat/platform/ios'
16
18
 
17
19
  import type { NSObjectProtocol } from '@octane-xplat/platform/ios'
@@ -22,370 +24,486 @@ type PlayerTime = ReturnType<AVPlayer['currentTime']>
22
24
  declare function CMTimeGetSeconds(time: PlayerTime): number
23
25
  declare function CMTimeMakeWithSeconds(seconds: number, preferredTimescale: number): PlayerTime
24
26
 
27
+ /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
25
28
  export const createAudioPlayer = (): AudioPlayer => {
26
- const listeners = new Set<(snapshot: AudioSnapshot) => void>()
27
- const session = AVAudioSession.sharedInstance()
28
- // NativeScript's ambient const enums cannot be read with verbatimModuleSyntax.
29
- const interruptionBegan = 1 // AVAudioSessionInterruptionType.Began
30
- const interruptionEnded = 0 // AVAudioSessionInterruptionType.Ended
31
- const interruptionShouldResume = 1 // AVAudioSessionInterruptionOptions.ShouldResume
32
- const statusFailed = 2 // AVPlayerStatus.Failed
33
- const notifyOthersOnDeactivation = 1 as AVAudioSessionSetActiveOptions
34
- // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
35
- // needs MediaPlayer.framework linked AND metadata-generated — plugin
36
- // LDFLAGS alone don't reach the metadata scan, so the MP* globals can be
37
- // undefined. Playback still works; guard and report systemControls:false.
38
- const hasMediaPlayer =
39
- typeof MPRemoteCommandCenter !== 'undefined' &&
40
- typeof MPNowPlayingInfoCenter !== 'undefined' &&
41
- // The runtime metadata keys may be absent when MediaPlayer isn't linked.
42
- typeof (globalThis as any).MPMediaItemPropertyPlaybackDuration !== 'undefined' &&
43
- typeof (globalThis as any).MPRemoteCommandHandlerStatus !== 'undefined'
44
-
45
- const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : undefined
46
- const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : undefined
47
- let queue: Track[] = []
48
- let index = -1
49
- let player: AVPlayer | undefined
50
- let state: AudioSnapshot['state'] = 'idle'
51
- let error: Error | undefined
52
- let disposed = false
53
- let wasPlayingBeforeInterruption = false
54
- let timer: ReturnType<typeof setInterval> | undefined
55
- let endObserver: NSObjectProtocol | undefined
56
- let failureObserver: NSObjectProtocol | undefined
57
- let interruptionObserver: NSObjectProtocol | undefined
58
- const remoteTargets: Array<{ command: any; token: any }> = []
59
-
60
- const current = () => queue[index]
61
- const seconds = (time: PlayerTime) => {
62
- const value = CMTimeGetSeconds(time)
63
- return Number.isFinite(value) && value > 0 ? value : 0
64
- }
65
-
66
- const snapshot = (): AudioSnapshot => ({
67
- state,
68
- track: current(),
69
- currentTime: player ? seconds(player.currentTime()) : 0,
70
- duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
71
- error,
72
- })
73
-
74
- const emit = () => {
75
- const value = snapshot()
76
- for (const listener of listeners) {
77
- listener(value)
78
- }
79
- }
80
-
81
- const updateNowPlaying = () => {
82
- if (!nowPlaying) {
83
- return
84
- }
85
-
86
- const track = current()
87
- if (!track) {
88
- nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
89
- return
90
- }
91
-
92
- const info = NSMutableDictionary.dictionary()
93
- info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle)
94
- if (track.artist) {
95
- info.setObjectForKey(track.artist, MPMediaItemPropertyArtist)
96
- }
97
-
98
- if (track.album) {
99
- info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle)
100
- }
101
-
102
- info.setObjectForKey(
103
- snapshot().duration,
104
- (globalThis as any).MPMediaItemPropertyPlaybackDuration,
105
- )
106
-
107
- info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime)
108
- info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate)
109
- nowPlaying.nowPlayingInfo = info
110
- }
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
-
119
- const clearTrack = () => {
120
- if (endObserver) {
121
- NSNotificationCenter.defaultCenter.removeObserver(endObserver)
122
- endObserver = undefined
123
- }
124
-
125
- if (failureObserver) {
126
- NSNotificationCenter.defaultCenter.removeObserver(failureObserver)
127
- failureObserver = undefined
128
- }
129
-
130
- player?.pause()
131
- player = undefined
132
- }
133
-
134
- const load = async (autoplay = false) => {
135
- clearTrack()
136
- wasPlayingBeforeInterruption = false
137
- const track = current()
138
- if (!track) {
139
- state = 'idle'
140
- updateNowPlaying()
141
- emit()
142
- return
143
- }
144
-
145
- state = 'loading'
146
- error = undefined
147
- emit()
148
- try {
149
- const url = track.source.startsWith('/')
150
- ? NSURL.fileURLWithPath(track.source)
151
- : NSURL.URLWithString(track.source)
152
-
153
- const item = AVPlayerItem.playerItemWithURL(url)
154
- player = AVPlayer.playerWithPlayerItem(item)
155
- endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
156
- AVPlayerItemDidPlayToEndTimeNotification,
157
- item,
158
- NSOperationQueue.mainQueue,
159
- () => void advance(1),
160
- )
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
-
178
- state = 'paused'
179
- updateNowPlaying()
180
- emit()
181
- if (autoplay) {
182
- await play()
183
- }
184
- } catch (cause) {
185
- error = cause instanceof Error ? cause : new Error(String(cause))
186
- state = 'error'
187
- emit()
188
- throw error
189
- }
190
- }
191
-
192
- const advance = async (delta: number) => {
193
- if (!queue.length || disposed) {
194
- return
195
- }
196
-
197
- if (index + delta >= queue.length) {
198
- state = 'ended'
199
- player?.pause()
200
- emit()
201
- return
202
- }
203
-
204
- index = Math.max(0, index + delta)
205
- await load(true)
206
- }
207
-
208
- const play = async () => {
209
- if (!player || disposed) {
210
- return
211
- }
212
-
213
- const category = AVAudioSessionCategoryPlayback
214
- session.setCategoryModeOptionsError(
215
- category,
216
- AVAudioSessionModeDefault,
217
- 0 as AVAudioSessionCategoryOptions,
218
- undefined,
219
- )
220
-
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
-
228
- player.play()
229
- state = 'playing'
230
- updateNowPlaying()
231
- emit()
232
- }
233
-
234
- const pause = async () => {
235
- // An explicit pause must not be auto-resumed by a pending interruption
236
- // Ended notification.
237
- wasPlayingBeforeInterruption = false
238
- player?.pause()
239
- state = 'paused'
240
- updateNowPlaying()
241
- emit()
242
- }
243
-
244
- const addRemoteTarget = (command: any, handler: (event?: any) => void) => {
245
- const token = command.addTargetWithHandler((event: any) => {
246
- handler(event)
247
- return (globalThis as any).MPRemoteCommandHandlerStatus.Success
248
- })
249
-
250
- remoteTargets.push({ command, token })
251
- }
252
-
253
- if (commandCenter) {
254
- addRemoteTarget(commandCenter.playCommand, () => void play())
255
- addRemoteTarget(commandCenter.pauseCommand, () => void pause())
256
- addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1))
257
- addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1))
258
- addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
259
- if (player && Number.isFinite(event.positionTime)) {
260
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600))
261
- updateNowPlaying()
262
- emit()
263
- }
264
- })
265
- }
266
-
267
- interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
268
- AVAudioSessionInterruptionNotification,
269
- null,
270
- NSOperationQueue.mainQueue,
271
- (notification) => {
272
- const type = notification.userInfo?.objectForKey(
273
- AVAudioSessionInterruptionTypeKey,
274
- )?.unsignedIntegerValue
275
-
276
- if (type === interruptionBegan) {
277
- wasPlayingBeforeInterruption = state === 'playing'
278
- player?.pause()
279
- state = 'paused'
280
- emit()
281
- } else if (type === interruptionEnded && wasPlayingBeforeInterruption) {
282
- const options =
283
- notification.userInfo?.objectForKey(AVAudioSessionInterruptionOptionKey)
284
- ?.unsignedIntegerValue ?? 0
285
-
286
- wasPlayingBeforeInterruption = false
287
- if ((options & interruptionShouldResume) !== 0) {
288
- void play()
289
- }
290
- }
291
- },
292
- )
293
-
294
- return {
295
- capabilities: (): AudioCapabilities => ({
296
- supported: true,
297
- backgroundPlayback: true,
298
- systemControls: hasMediaPlayer,
299
- userGestureRequired: false,
300
- interruptions: true,
301
- }),
302
- snapshot,
303
- subscribe: (listener) => {
304
- listeners.add(listener)
305
- listener(snapshot())
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
-
315
- updateNowPlaying()
316
- emit()
317
- }, 500)
318
-
319
- return () => {
320
- listeners.delete(listener)
321
- if (!listeners.size && timer) {
322
- clearInterval(timer)
323
- timer = undefined
324
- }
325
- }
326
- },
327
- setQueue: async (tracks, startAt = 0) => {
328
- if (disposed) {
329
- throw new Error('AudioPlayer is disposed')
330
- }
331
-
332
- queue = [...tracks]
333
- index = queue.length
334
- ? Math.max(
335
- 0,
336
- Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1),
337
- )
338
- : -1
339
-
340
- await load()
341
- },
342
- play,
343
- pause,
344
- seek: async (value) => {
345
- if (!player || !Number.isFinite(value)) {
346
- return
347
- }
348
-
349
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600))
350
- updateNowPlaying()
351
- emit()
352
- },
353
- dispose: () => {
354
- if (disposed) {
355
- return
356
- }
357
-
358
- disposed = true
359
- clearTrack()
360
- if (interruptionObserver) {
361
- NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver)
362
- }
363
-
364
- interruptionObserver = undefined
365
- for (const { command, token } of remoteTargets) {
366
- command.removeTarget(token)
367
- }
368
-
369
- remoteTargets.length = 0
370
- if (timer) {
371
- clearInterval(timer)
372
- }
373
-
374
- timer = undefined
375
- if (nowPlaying) {
376
- nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
377
- }
378
-
379
- // The Objective-C error-out argument is intentionally null at runtime;
380
- // NativeScript's generated type only permits Reference<NSError> | undefined.
381
- const noErrorOut = null as unknown as Parameters<typeof session.setActiveWithOptionsError>[2]
382
-
383
- session.setActiveWithOptionsError(false, notifyOthersOnDeactivation, noErrorOut)
384
-
385
- listeners.clear()
386
- queue = []
387
- index = -1
388
- state = 'idle'
389
- },
390
- }
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
+ }
391
509
  }