@octane-xplat/audio 0.8.0 → 0.9.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,271 +1,321 @@
1
- import type {
2
- AudioCapabilities,
3
- AudioPlayer,
4
- AudioSnapshot,
5
- Track,
6
- } from "./types";
1
+ import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
7
2
 
8
3
  // CoreMedia is available at runtime but omitted from NativeScript's common
9
4
  // ambient references. Reuse AVPlayer's time type for this bridge slice.
10
- type PlayerTime = ReturnType<AVPlayer["currentTime"]>;
11
- declare function CMTimeGetSeconds(time: PlayerTime): number;
12
- declare function CMTimeMakeWithSeconds(seconds: number, preferredTimescale: number): PlayerTime;
5
+ type PlayerTime = ReturnType<AVPlayer['currentTime']>
6
+ declare function CMTimeGetSeconds(time: PlayerTime): number
7
+ declare function CMTimeMakeWithSeconds(seconds: number, preferredTimescale: number): PlayerTime
13
8
 
14
9
  export const createAudioPlayer = (): AudioPlayer => {
15
- const listeners = new Set<(snapshot: AudioSnapshot) => void>();
16
- const session = AVAudioSession.sharedInstance();
17
- // NativeScript's ambient const enums cannot be read with verbatimModuleSyntax.
18
- const interruptionBegan = 1; // AVAudioSessionInterruptionType.Began
19
- const interruptionShouldResume = 1; // AVAudioSessionInterruptionOptions.ShouldResume
20
- const notifyOthersOnDeactivation = 1 as AVAudioSessionSetActiveOptions;
21
- // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
22
- // needs MediaPlayer.framework linked AND metadata-generated — plugin
23
- // LDFLAGS alone don't reach the metadata scan, so the MP* globals can be
24
- // undefined. Playback still works; guard and report systemControls:false.
25
- const hasMediaPlayer =
26
- typeof MPRemoteCommandCenter !== 'undefined' &&
27
- typeof MPNowPlayingInfoCenter !== 'undefined' &&
28
- // The runtime metadata keys may be absent when MediaPlayer isn't linked.
29
- typeof (globalThis as any).MPMediaItemPropertyPlaybackDuration !== 'undefined' &&
30
- typeof (globalThis as any).MPRemoteCommandHandlerStatus !== 'undefined';
31
-
32
- const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : undefined;
33
- const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : undefined;
34
- let queue: Track[] = [];
35
- let index = -1;
36
- let player: AVPlayer | undefined;
37
- let state: AudioSnapshot["state"] = "idle";
38
- let error: Error | undefined;
39
- let disposed = false;
40
- let wasPlayingBeforeInterruption = false;
41
- let timer: ReturnType<typeof setInterval> | undefined;
42
- let endObserver: NSObjectProtocol | undefined;
43
- let interruptionObserver: NSObjectProtocol | undefined;
44
- const remoteTargets: Array<{ command: any; token: any }> = [];
45
-
46
- const current = () => queue[index];
47
- const seconds = (time: PlayerTime) => {
48
- const value = CMTimeGetSeconds(time);
49
- return Number.isFinite(value) && value > 0 ? value : 0;
50
- };
51
-
52
- const snapshot = (): AudioSnapshot => ({
53
- state,
54
- track: current(),
55
- currentTime: player ? seconds(player.currentTime()) : 0,
56
- duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
57
- error,
58
- });
59
-
60
- const emit = () => {
61
- const value = snapshot();
62
- for (const listener of listeners) {listener(value);}
63
- };
64
-
65
- const updateNowPlaying = () => {
66
- if (!nowPlaying) {return;}
67
- const track = current();
68
- if (!track) {
69
- nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>;
70
- return;
71
- }
72
-
73
- const info = NSMutableDictionary.dictionary();
74
- info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle);
75
- if (track.artist) {info.setObjectForKey(track.artist, MPMediaItemPropertyArtist);}
76
- if (track.album) {info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle);}
77
- info.setObjectForKey(
78
- snapshot().duration,
79
- (globalThis as any).MPMediaItemPropertyPlaybackDuration,
80
- );
81
-
82
- info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime);
83
- info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate);
84
- nowPlaying.nowPlayingInfo = info;
85
- };
86
-
87
- const clearTrack = () => {
88
- if (endObserver) {
89
- NSNotificationCenter.defaultCenter.removeObserver(endObserver);
90
- endObserver = undefined;
91
- }
92
-
93
- player?.pause();
94
- player = undefined;
95
- };
96
-
97
- const load = async (autoplay = false) => {
98
- clearTrack();
99
- const track = current();
100
- if (!track) {
101
- state = "idle";
102
- updateNowPlaying();
103
- emit();
104
- return;
105
- }
106
-
107
- state = "loading";
108
- error = undefined;
109
- emit();
110
- try {
111
- const url = track.source.startsWith("/")
112
- ? NSURL.fileURLWithPath(track.source)
113
- : NSURL.URLWithString(track.source);
114
-
115
- const item = AVPlayerItem.playerItemWithURL(url);
116
- player = AVPlayer.playerWithPlayerItem(item);
117
- endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
118
- AVPlayerItemDidPlayToEndTimeNotification,
119
- item,
120
- NSOperationQueue.mainQueue,
121
- () => void advance(1),
122
- );
123
-
124
- state = "paused";
125
- updateNowPlaying();
126
- emit();
127
- if (autoplay) {await play();}
128
- } catch (cause) {
129
- error = cause instanceof Error ? cause : new Error(String(cause));
130
- state = "error";
131
- emit();
132
- throw error;
133
- }
134
- };
135
-
136
- const advance = async (delta: number) => {
137
- if (!queue.length || disposed) {return;}
138
- if (index + delta >= queue.length) {
139
- state = "ended";
140
- player?.pause();
141
- emit();
142
- return;
143
- }
144
-
145
- index = Math.max(0, index + delta);
146
- await load(true);
147
- };
148
-
149
- const play = async () => {
150
- if (!player || disposed) {return;}
151
- const category = AVAudioSessionCategoryPlayback;
152
- session.setCategoryModeOptionsError(category, AVAudioSessionModeDefault, 0 as AVAudioSessionCategoryOptions, undefined);
153
- session.setActiveWithOptionsError(true, 0 as AVAudioSessionSetActiveOptions, undefined);
154
- player.play();
155
- state = "playing";
156
- updateNowPlaying();
157
- emit();
158
- };
159
-
160
- const pause = async () => {
161
- player?.pause();
162
- state = "paused";
163
- updateNowPlaying();
164
- emit();
165
- };
166
-
167
- const addRemoteTarget = (command: any, handler: (event?: any) => void) => {
168
- const token = command.addTargetWithHandler((event: any) => {
169
- handler(event);
170
- return (globalThis as any).MPRemoteCommandHandlerStatus.Success;
171
- });
172
-
173
- remoteTargets.push({ command, token });
174
- };
175
-
176
- if (commandCenter) {
177
- addRemoteTarget(commandCenter.playCommand, () => void play());
178
- addRemoteTarget(commandCenter.pauseCommand, () => void pause());
179
- addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1));
180
- addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1));
181
- addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
182
- if (player && Number.isFinite(event.positionTime)) {
183
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600));
184
- updateNowPlaying();
185
- emit();
186
- }
187
- });
188
- }
189
-
190
- interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
191
- AVAudioSessionInterruptionNotification,
192
- null,
193
- NSOperationQueue.mainQueue,
194
- (notification) => {
195
- const type = notification.userInfo.objectForKey(AVAudioSessionInterruptionTypeKey).unsignedIntegerValue;
196
- if (type === interruptionBegan) {
197
- wasPlayingBeforeInterruption = state === "playing";
198
- player?.pause();
199
- state = "paused";
200
- emit();
201
- } else if (wasPlayingBeforeInterruption) {
202
- const options = notification.userInfo.objectForKey(AVAudioSessionInterruptionOptionKey)?.unsignedIntegerValue ?? 0;
203
- wasPlayingBeforeInterruption = false;
204
- if ((options & interruptionShouldResume) !== 0) {
205
- void play();
206
- }
207
- }
208
- },
209
- );
210
-
211
- return {
212
- capabilities: (): AudioCapabilities => ({
213
- supported: true,
214
- backgroundPlayback: true,
215
- systemControls: hasMediaPlayer,
216
- userGestureRequired: false,
217
- interruptions: true,
218
- }),
219
- snapshot,
220
- subscribe: (listener) => {
221
- listeners.add(listener);
222
- listener(snapshot());
223
- timer ??= setInterval(() => {
224
- updateNowPlaying();
225
- emit();
226
- }, 500);
227
-
228
- return () => {
229
- listeners.delete(listener);
230
- if (!listeners.size && timer) {
231
- clearInterval(timer);
232
- timer = undefined;
233
- }
234
- };
235
- },
236
- setQueue: async (tracks, startAt = 0) => {
237
- if (disposed) {throw new Error("AudioPlayer is disposed");}
238
- queue = [...tracks];
239
- index = queue.length
240
- ? Math.max(0, Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1))
241
- : -1;
242
-
243
- await load();
244
- },
245
- play,
246
- pause,
247
- seek: async (value) => {
248
- if (!player || !Number.isFinite(value)) {return;}
249
- player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600));
250
- updateNowPlaying();
251
- emit();
252
- },
253
- dispose: () => {
254
- if (disposed) {return;}
255
- disposed = true;
256
- clearTrack();
257
- if (interruptionObserver) {NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver);}
258
- interruptionObserver = undefined;
259
- for (const { command, token } of remoteTargets) {command.removeTarget(token);}
260
- remoteTargets.length = 0;
261
- if (timer) {clearInterval(timer);}
262
- timer = undefined;
263
- if (nowPlaying) {nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>;}
264
- session.setActiveWithOptionsError(false, notifyOthersOnDeactivation, undefined);
265
- listeners.clear();
266
- queue = [];
267
- index = -1;
268
- state = "idle";
269
- },
270
- };
271
- };
10
+ const listeners = new Set<(snapshot: AudioSnapshot) => void>()
11
+ const session = AVAudioSession.sharedInstance()
12
+ // NativeScript's ambient const enums cannot be read with verbatimModuleSyntax.
13
+ const interruptionBegan = 1 // AVAudioSessionInterruptionType.Began
14
+ const interruptionShouldResume = 1 // AVAudioSessionInterruptionOptions.ShouldResume
15
+ const notifyOthersOnDeactivation = 1 as AVAudioSessionSetActiveOptions
16
+ // Lock-screen transport (MPRemoteCommandCenter / MPNowPlayingInfoCenter)
17
+ // needs MediaPlayer.framework linked AND metadata-generated — plugin
18
+ // LDFLAGS alone don't reach the metadata scan, so the MP* globals can be
19
+ // undefined. Playback still works; guard and report systemControls:false.
20
+ const hasMediaPlayer =
21
+ typeof MPRemoteCommandCenter !== 'undefined' &&
22
+ typeof MPNowPlayingInfoCenter !== 'undefined' &&
23
+ // The runtime metadata keys may be absent when MediaPlayer isn't linked.
24
+ typeof (globalThis as any).MPMediaItemPropertyPlaybackDuration !== 'undefined' &&
25
+ typeof (globalThis as any).MPRemoteCommandHandlerStatus !== 'undefined'
26
+
27
+ const commandCenter = hasMediaPlayer ? MPRemoteCommandCenter.sharedCommandCenter() : undefined
28
+ const nowPlaying = hasMediaPlayer ? MPNowPlayingInfoCenter.defaultCenter() : undefined
29
+ let queue: Track[] = []
30
+ let index = -1
31
+ let player: AVPlayer | undefined
32
+ let state: AudioSnapshot['state'] = 'idle'
33
+ let error: Error | undefined
34
+ let disposed = false
35
+ let wasPlayingBeforeInterruption = false
36
+ let timer: ReturnType<typeof setInterval> | undefined
37
+ let endObserver: NSObjectProtocol | undefined
38
+ let interruptionObserver: NSObjectProtocol | undefined
39
+ const remoteTargets: Array<{ command: any; token: any }> = []
40
+
41
+ const current = () => queue[index]
42
+ const seconds = (time: PlayerTime) => {
43
+ const value = CMTimeGetSeconds(time)
44
+ return Number.isFinite(value) && value > 0 ? value : 0
45
+ }
46
+
47
+ const snapshot = (): AudioSnapshot => ({
48
+ state,
49
+ track: current(),
50
+ currentTime: player ? seconds(player.currentTime()) : 0,
51
+ duration: player?.currentItem ? seconds(player.currentItem.duration) : 0,
52
+ error,
53
+ })
54
+
55
+ const emit = () => {
56
+ const value = snapshot()
57
+ for (const listener of listeners) {
58
+ listener(value)
59
+ }
60
+ }
61
+
62
+ const updateNowPlaying = () => {
63
+ if (!nowPlaying) {
64
+ return
65
+ }
66
+
67
+ const track = current()
68
+ if (!track) {
69
+ nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
70
+ return
71
+ }
72
+
73
+ const info = NSMutableDictionary.dictionary()
74
+ info.setObjectForKey(track.title ?? track.id, MPMediaItemPropertyTitle)
75
+ if (track.artist) {
76
+ info.setObjectForKey(track.artist, MPMediaItemPropertyArtist)
77
+ }
78
+
79
+ if (track.album) {
80
+ info.setObjectForKey(track.album, MPMediaItemPropertyAlbumTitle)
81
+ }
82
+
83
+ info.setObjectForKey(
84
+ snapshot().duration,
85
+ (globalThis as any).MPMediaItemPropertyPlaybackDuration,
86
+ )
87
+
88
+ info.setObjectForKey(snapshot().currentTime, MPNowPlayingInfoPropertyElapsedPlaybackTime)
89
+ info.setObjectForKey(player?.rate ?? 0, MPNowPlayingInfoPropertyPlaybackRate)
90
+ nowPlaying.nowPlayingInfo = info
91
+ }
92
+
93
+ const clearTrack = () => {
94
+ if (endObserver) {
95
+ NSNotificationCenter.defaultCenter.removeObserver(endObserver)
96
+ endObserver = undefined
97
+ }
98
+
99
+ player?.pause()
100
+ player = undefined
101
+ }
102
+
103
+ const load = async (autoplay = false) => {
104
+ clearTrack()
105
+ const track = current()
106
+ if (!track) {
107
+ state = 'idle'
108
+ updateNowPlaying()
109
+ emit()
110
+ return
111
+ }
112
+
113
+ state = 'loading'
114
+ error = undefined
115
+ emit()
116
+ try {
117
+ const url = track.source.startsWith('/')
118
+ ? NSURL.fileURLWithPath(track.source)
119
+ : NSURL.URLWithString(track.source)
120
+
121
+ const item = AVPlayerItem.playerItemWithURL(url)
122
+ player = AVPlayer.playerWithPlayerItem(item)
123
+ endObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
124
+ AVPlayerItemDidPlayToEndTimeNotification,
125
+ item,
126
+ NSOperationQueue.mainQueue,
127
+ () => void advance(1),
128
+ )
129
+
130
+ state = 'paused'
131
+ updateNowPlaying()
132
+ emit()
133
+ if (autoplay) {
134
+ await play()
135
+ }
136
+ } catch (cause) {
137
+ error = cause instanceof Error ? cause : new Error(String(cause))
138
+ state = 'error'
139
+ emit()
140
+ throw error
141
+ }
142
+ }
143
+
144
+ const advance = async (delta: number) => {
145
+ if (!queue.length || disposed) {
146
+ return
147
+ }
148
+
149
+ if (index + delta >= queue.length) {
150
+ state = 'ended'
151
+ player?.pause()
152
+ emit()
153
+ return
154
+ }
155
+
156
+ index = Math.max(0, index + delta)
157
+ await load(true)
158
+ }
159
+
160
+ const play = async () => {
161
+ if (!player || disposed) {
162
+ return
163
+ }
164
+
165
+ const category = AVAudioSessionCategoryPlayback
166
+ session.setCategoryModeOptionsError(
167
+ category,
168
+ AVAudioSessionModeDefault,
169
+ 0 as AVAudioSessionCategoryOptions,
170
+ undefined,
171
+ )
172
+
173
+ session.setActiveWithOptionsError(true, 0 as AVAudioSessionSetActiveOptions, undefined)
174
+ player.play()
175
+ state = 'playing'
176
+ updateNowPlaying()
177
+ emit()
178
+ }
179
+
180
+ const pause = async () => {
181
+ player?.pause()
182
+ state = 'paused'
183
+ updateNowPlaying()
184
+ emit()
185
+ }
186
+
187
+ const addRemoteTarget = (command: any, handler: (event?: any) => void) => {
188
+ const token = command.addTargetWithHandler((event: any) => {
189
+ handler(event)
190
+ return (globalThis as any).MPRemoteCommandHandlerStatus.Success
191
+ })
192
+
193
+ remoteTargets.push({ command, token })
194
+ }
195
+
196
+ if (commandCenter) {
197
+ addRemoteTarget(commandCenter.playCommand, () => void play())
198
+ addRemoteTarget(commandCenter.pauseCommand, () => void pause())
199
+ addRemoteTarget(commandCenter.nextTrackCommand, () => void advance(1))
200
+ addRemoteTarget(commandCenter.previousTrackCommand, () => void advance(-1))
201
+ addRemoteTarget(commandCenter.changePlaybackPositionCommand, (event) => {
202
+ if (player && Number.isFinite(event.positionTime)) {
203
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, event.positionTime), 600))
204
+ updateNowPlaying()
205
+ emit()
206
+ }
207
+ })
208
+ }
209
+
210
+ interruptionObserver = NSNotificationCenter.defaultCenter.addObserverForNameObjectQueueUsingBlock(
211
+ AVAudioSessionInterruptionNotification,
212
+ null,
213
+ NSOperationQueue.mainQueue,
214
+ (notification) => {
215
+ const type = notification.userInfo.objectForKey(
216
+ AVAudioSessionInterruptionTypeKey,
217
+ ).unsignedIntegerValue
218
+
219
+ if (type === interruptionBegan) {
220
+ wasPlayingBeforeInterruption = state === 'playing'
221
+ player?.pause()
222
+ state = 'paused'
223
+ emit()
224
+ } else if (wasPlayingBeforeInterruption) {
225
+ const options =
226
+ notification.userInfo.objectForKey(AVAudioSessionInterruptionOptionKey)
227
+ ?.unsignedIntegerValue ?? 0
228
+
229
+ wasPlayingBeforeInterruption = false
230
+ if ((options & interruptionShouldResume) !== 0) {
231
+ void play()
232
+ }
233
+ }
234
+ },
235
+ )
236
+
237
+ return {
238
+ capabilities: (): AudioCapabilities => ({
239
+ supported: true,
240
+ backgroundPlayback: true,
241
+ systemControls: hasMediaPlayer,
242
+ userGestureRequired: false,
243
+ interruptions: true,
244
+ }),
245
+ snapshot,
246
+ subscribe: (listener) => {
247
+ listeners.add(listener)
248
+ listener(snapshot())
249
+ timer ??= setInterval(() => {
250
+ updateNowPlaying()
251
+ emit()
252
+ }, 500)
253
+
254
+ return () => {
255
+ listeners.delete(listener)
256
+ if (!listeners.size && timer) {
257
+ clearInterval(timer)
258
+ timer = undefined
259
+ }
260
+ }
261
+ },
262
+ setQueue: async (tracks, startAt = 0) => {
263
+ if (disposed) {
264
+ throw new Error('AudioPlayer is disposed')
265
+ }
266
+
267
+ queue = [...tracks]
268
+ index = queue.length
269
+ ? Math.max(
270
+ 0,
271
+ Math.min(Number.isFinite(startAt) ? Math.floor(startAt) : 0, queue.length - 1),
272
+ )
273
+ : -1
274
+
275
+ await load()
276
+ },
277
+ play,
278
+ pause,
279
+ seek: async (value) => {
280
+ if (!player || !Number.isFinite(value)) {
281
+ return
282
+ }
283
+
284
+ player.seekToTime(CMTimeMakeWithSeconds(Math.max(0, value), 600))
285
+ updateNowPlaying()
286
+ emit()
287
+ },
288
+ dispose: () => {
289
+ if (disposed) {
290
+ return
291
+ }
292
+
293
+ disposed = true
294
+ clearTrack()
295
+ if (interruptionObserver) {
296
+ NSNotificationCenter.defaultCenter.removeObserver(interruptionObserver)
297
+ }
298
+
299
+ interruptionObserver = undefined
300
+ for (const { command, token } of remoteTargets) {
301
+ command.removeTarget(token)
302
+ }
303
+
304
+ remoteTargets.length = 0
305
+ if (timer) {
306
+ clearInterval(timer)
307
+ }
308
+
309
+ timer = undefined
310
+ if (nowPlaying) {
311
+ nowPlaying.nowPlayingInfo = null as unknown as NSDictionary<string, any>
312
+ }
313
+
314
+ session.setActiveWithOptionsError(false, notifyOthersOnDeactivation, undefined)
315
+ listeners.clear()
316
+ queue = []
317
+ index = -1
318
+ state = 'idle'
319
+ },
320
+ }
321
+ }
package/src/audio.ts CHANGED
@@ -1,10 +1,16 @@
1
- import { Application } from "@nativescript/core";
2
- import { createAudioPlayer as createAndroidAudioPlayer } from "./audio.android";
3
- import { createAudioPlayer as createIOSAudioPlayer } from "./audio.ios";
4
- import type { AudioPlayer } from "./types";
1
+ import { Application } from '@nativescript/core'
2
+ import { createAudioPlayer as createAndroidAudioPlayer } from './audio.android'
3
+ import { createAudioPlayer as createIOSAudioPlayer } from './audio.ios'
4
+ import type { AudioPlayer } from './types'
5
5
 
6
6
  export const createAudioPlayer = (): AudioPlayer => {
7
- if (Application.android) {return createAndroidAudioPlayer();}
8
- if (Application.ios) {return createIOSAudioPlayer();}
9
- throw new Error("@octane-xplat/audio requires iOS or Android");
10
- };
7
+ if (Application.android) {
8
+ return createAndroidAudioPlayer()
9
+ }
10
+
11
+ if (Application.ios) {
12
+ return createIOSAudioPlayer()
13
+ }
14
+
15
+ throw new Error('@octane-xplat/audio requires iOS or Android')
16
+ }