@octane-xplat/audio 0.0.0-nightly.g2e22171

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.
@@ -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
+ }
package/src/audio.ts ADDED
@@ -0,0 +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'
5
+
6
+ export const createAudioPlayer = (): AudioPlayer => {
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
+ }
@@ -0,0 +1,183 @@
1
+ import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
2
+
3
+ export const createAudioPlayer = (): AudioPlayer => {
4
+ const audio = new Audio()
5
+ const listeners = new Set<(value: AudioSnapshot) => void>()
6
+ let queue: Track[] = []
7
+ let index = -1
8
+ let state: AudioSnapshot['state'] = 'idle'
9
+ let error: Error | undefined
10
+ let disposed = false
11
+ const current = () => queue[index]
12
+ const snapshot = (): AudioSnapshot => ({
13
+ state,
14
+ track: current(),
15
+ currentTime: audio.currentTime || 0,
16
+ duration: Number.isFinite(audio.duration) ? audio.duration : 0,
17
+ error,
18
+ })
19
+
20
+ const emit = () => {
21
+ const value = snapshot()
22
+ for (const listener of listeners) {
23
+ listener(value)
24
+ }
25
+ }
26
+
27
+ const setTrack = () => {
28
+ const track = current()
29
+ if (!track) {
30
+ audio.removeAttribute('src')
31
+ state = 'idle'
32
+ emit()
33
+ return
34
+ }
35
+
36
+ audio.src = track.source
37
+ state = 'loading'
38
+ if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
39
+ navigator.mediaSession.metadata = new MediaMetadata({
40
+ title: track.title ?? track.id,
41
+ artist: track.artist ?? '',
42
+ album: track.album ?? '',
43
+ })
44
+
45
+ navigator.mediaSession.setActionHandler('play', () => {
46
+ void audio.play()
47
+ })
48
+
49
+ navigator.mediaSession.setActionHandler('pause', () => audio.pause())
50
+ navigator.mediaSession.setActionHandler('seekto', (event) => {
51
+ if (event.seekTime != null) {
52
+ audio.currentTime = event.seekTime
53
+ }
54
+ })
55
+
56
+ navigator.mediaSession.setActionHandler('nexttrack', () => {
57
+ void advance(1)
58
+ })
59
+
60
+ navigator.mediaSession.setActionHandler('previoustrack', () => {
61
+ void advance(-1)
62
+ })
63
+ }
64
+
65
+ emit()
66
+ }
67
+
68
+ const advance = async (delta: number) => {
69
+ if (!queue.length) {
70
+ return
71
+ }
72
+
73
+ if (delta > 0 && index + 1 >= queue.length) {
74
+ audio.pause()
75
+ state = 'ended'
76
+ emit()
77
+ return
78
+ }
79
+
80
+ index = Math.max(0, Math.min(index + delta, queue.length - 1))
81
+ setTrack()
82
+ try {
83
+ await audio.play()
84
+ } catch (cause) {
85
+ error = cause instanceof Error ? cause : new Error(String(cause))
86
+ state = 'error'
87
+ emit()
88
+ }
89
+ }
90
+
91
+ for (const event of [
92
+ 'timeupdate',
93
+ 'durationchange',
94
+ 'play',
95
+ 'playing',
96
+ 'pause',
97
+ 'ended',
98
+ 'waiting',
99
+ 'error',
100
+ ]) {
101
+ audio.addEventListener(event, () => {
102
+ if (event === 'play') {
103
+ state = 'loading'
104
+ } else if (event === 'playing') {
105
+ state = 'playing'
106
+ } else if (event === 'pause' && state !== 'ended') {
107
+ state = 'paused'
108
+ } else if (event === 'ended') {
109
+ state = 'ended'
110
+ void advance(1)
111
+ return
112
+ } else if (event === 'error') {
113
+ state = 'error'
114
+ error = new Error('Audio playback failed')
115
+ } else if (event === 'waiting') {
116
+ state = 'loading'
117
+ }
118
+
119
+ emit()
120
+ })
121
+ }
122
+
123
+ return {
124
+ capabilities: (): AudioCapabilities => ({
125
+ supported: true,
126
+ backgroundPlayback: false,
127
+ systemControls: typeof navigator !== 'undefined' && 'mediaSession' in navigator,
128
+ userGestureRequired: true,
129
+ interruptions: false,
130
+ reason:
131
+ 'Background playback and OS interruption handling are unavailable on web; autoplay may require a user gesture.',
132
+ }),
133
+ snapshot,
134
+ subscribe: (listener) => {
135
+ listeners.add(listener)
136
+ listener(snapshot())
137
+ return () => listeners.delete(listener)
138
+ },
139
+ setQueue: async (tracks, startAt = 0) => {
140
+ if (disposed) {
141
+ throw new Error('AudioPlayer is disposed')
142
+ }
143
+
144
+ queue = [...tracks]
145
+ index = queue.length
146
+ ? Math.min(
147
+ Math.max(Number.isFinite(startAt) ? Math.floor(startAt) : 0, 0),
148
+ queue.length - 1,
149
+ )
150
+ : -1
151
+
152
+ error = undefined
153
+ setTrack()
154
+ },
155
+ play: async () => {
156
+ if (!disposed && current()) {
157
+ await audio.play()
158
+ }
159
+ },
160
+ pause: async () => {
161
+ audio.pause()
162
+ },
163
+ seek: async (seconds) => {
164
+ if (Number.isFinite(seconds)) {
165
+ audio.currentTime = Math.max(0, seconds)
166
+ }
167
+ },
168
+ dispose: () => {
169
+ disposed = true
170
+ audio.pause()
171
+ audio.removeAttribute('src')
172
+ audio.load()
173
+ listeners.clear()
174
+ queue = []
175
+ if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
176
+ navigator.mediaSession.metadata = null
177
+ for (const action of ['play', 'pause', 'seekto', 'nexttrack', 'previoustrack'] as const) {
178
+ navigator.mediaSession.setActionHandler(action, null)
179
+ }
180
+ }
181
+ },
182
+ }
183
+ }
@@ -0,0 +1,2 @@
1
+ export type * from './types'
2
+ export { createAudioPlayer } from './audio.macos'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { createAudioPlayer } from './audio'
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { createAudioPlayer } from './audio.web'
package/src/types.ts ADDED
@@ -0,0 +1,41 @@
1
+ export type Track = {
2
+ id: string
3
+ source: string
4
+ title?: string
5
+ artist?: string
6
+ album?: string
7
+ }
8
+
9
+ export type AudioCapabilities = {
10
+ supported: boolean
11
+ backgroundPlayback: boolean
12
+ systemControls: boolean
13
+ userGestureRequired: boolean
14
+ interruptions: boolean
15
+ reason?: string
16
+ }
17
+
18
+ export type PlaybackState = 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'error'
19
+
20
+ export type AudioSnapshot = {
21
+ state: PlaybackState
22
+ track?: Track
23
+ /** Current position in seconds. */
24
+ currentTime: number
25
+ /** Track length in seconds, or 0 until known. */
26
+ duration: number
27
+ error?: Error
28
+ }
29
+
30
+ export interface AudioPlayer {
31
+ capabilities(): AudioCapabilities
32
+ snapshot(): AudioSnapshot
33
+ subscribe(listener: (snapshot: AudioSnapshot) => void): () => void
34
+ setQueue(tracks: readonly Track[], startAt?: number): Promise<void>
35
+ play(): Promise<void>
36
+ pause(): Promise<void>
37
+ seek(seconds: number): Promise<void>
38
+ dispose(): void
39
+ }
40
+
41
+ export declare function createAudioPlayer(): AudioPlayer
@@ -0,0 +1 @@
1
+ export * from './types.js'
@@ -0,0 +1,36 @@
1
+ export type Track = {
2
+ id: string;
3
+ source: string;
4
+ title?: string;
5
+ artist?: string;
6
+ album?: string;
7
+ };
8
+ export type AudioCapabilities = {
9
+ supported: boolean;
10
+ backgroundPlayback: boolean;
11
+ systemControls: boolean;
12
+ userGestureRequired: boolean;
13
+ interruptions: boolean;
14
+ reason?: string;
15
+ };
16
+ export type PlaybackState = 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'error';
17
+ export type AudioSnapshot = {
18
+ state: PlaybackState;
19
+ track?: Track;
20
+ /** Current position in seconds. */
21
+ currentTime: number;
22
+ /** Track length in seconds, or 0 until known. */
23
+ duration: number;
24
+ error?: Error;
25
+ };
26
+ export interface AudioPlayer {
27
+ capabilities(): AudioCapabilities;
28
+ snapshot(): AudioSnapshot;
29
+ subscribe(listener: (snapshot: AudioSnapshot) => void): () => void;
30
+ setQueue(tracks: readonly Track[], startAt?: number): Promise<void>;
31
+ play(): Promise<void>;
32
+ pause(): Promise<void>;
33
+ seek(seconds: number): Promise<void>;
34
+ dispose(): void;
35
+ }
36
+ export declare function createAudioPlayer(): AudioPlayer;