@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.ts CHANGED
@@ -5,13 +5,13 @@ import type { AudioPlayer } from './types'
5
5
 
6
6
  /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
7
7
  export const createAudioPlayer = (): AudioPlayer => {
8
- if (Application.android) {
9
- return createAndroidAudioPlayer()
10
- }
8
+ if (Application.android) {
9
+ return createAndroidAudioPlayer()
10
+ }
11
11
 
12
- if (Application.ios) {
13
- return createIOSAudioPlayer()
14
- }
12
+ if (Application.ios) {
13
+ return createIOSAudioPlayer()
14
+ }
15
15
 
16
- throw new Error('@octane-xplat/audio requires iOS or Android')
16
+ throw new Error('@octane-xplat/audio requires iOS or Android')
17
17
  }
package/src/audio.web.ts CHANGED
@@ -4,294 +4,307 @@ import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './typ
4
4
 
5
5
  /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
6
6
  export const createAudioPlayer = (): AudioPlayer => {
7
- const audio = new Audio()
8
- const listeners = new Set<(value: AudioSnapshot) => void>()
9
- let queue: Track[] = []
10
- let index = -1
11
- let state: AudioSnapshot['state'] = 'idle'
12
- let error: Error | undefined
13
- let disposed = false
14
- let generation = 0
15
- let playbackRate = 1
16
- let volume = 1
17
- let muted = false
18
- let queueComplete = true
19
- let waitingToResume = false
20
- const current = () => queue[index]
21
- const snapshot = (): AudioSnapshot => ({
22
- state,
23
- playbackRate,
24
- volume,
25
- muted,
26
- queueComplete,
27
- track: current(),
28
- currentTime: audio.currentTime || 0,
29
- duration: Number.isFinite(audio.duration) ? audio.duration : 0,
30
- error,
31
- })
32
-
33
- const emit = () => {
34
- const value = snapshot()
35
- const ownGeneration = generation
36
- for (const listener of listeners) {
37
- if (disposed || ownGeneration !== generation) {
38
- break
39
- }
40
-
41
- listener(value)
42
- }
43
- }
44
-
45
- const updateMetadata = () => {
46
- const track = current()
47
- if (!track) {
48
- if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
49
- navigator.mediaSession.metadata = null
50
- }
51
-
52
- return
53
- }
54
- if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
55
- navigator.mediaSession.metadata = new MediaMetadata({
56
- title: track.title ?? track.id,
57
- artist: track.artist ?? '',
58
- album: track.album ?? '',
59
- })
60
-
61
- navigator.mediaSession.setActionHandler('play', () => {
62
- void play().catch(() => {})
63
- })
64
-
65
- navigator.mediaSession.setActionHandler('pause', () => {
66
- void pause()
67
- })
68
-
69
- navigator.mediaSession.setActionHandler('seekto', (event) => {
70
- if (event.seekTime != null) {
71
- audio.currentTime = event.seekTime
72
- }
73
- })
74
-
75
- navigator.mediaSession.setActionHandler('nexttrack', () => {
76
- void advance(1)
77
- })
78
-
79
- navigator.mediaSession.setActionHandler('previoustrack', () => {
80
- void advance(-1)
81
- })
82
- }
83
- }
84
-
85
- const setTrack = () => {
86
- generation++
87
- error = undefined
88
- const track = current()
89
- if (!track) {
90
- audio.removeAttribute('src')
91
- state = 'idle'
92
- updateMetadata()
93
- emit()
94
- return
95
- }
96
-
97
- audio.src = track.source
98
- audio.playbackRate = playbackRate
99
- audio.preservesPitch = true
100
- audio.volume = volume
101
- audio.muted = muted
102
- state = 'loading'
103
- updateMetadata()
104
- emit()
105
- }
106
-
107
- const advance = async (delta: number) => {
108
- if (!queue.length) {
109
- return
110
- }
111
-
112
- if (delta > 0 && index + 1 >= queue.length) {
113
- state = queueComplete ? 'ended' : 'waiting'
114
- waitingToResume = !queueComplete
115
- audio.pause()
116
- emit()
117
- return
118
- }
119
-
120
- index = Math.max(0, Math.min(index + delta, queue.length - 1))
121
- setTrack()
122
- const ownGeneration = generation
123
- try {
124
- await audio.play()
125
- } catch (cause) {
126
- if (disposed || ownGeneration !== generation) {
127
- return
128
- }
129
-
130
- error = cause instanceof Error ? cause : new Error(String(cause))
131
- state = 'error'
132
- emit()
133
- }
134
- }
135
-
136
- for (const event of [
137
- 'timeupdate',
138
- 'durationchange',
139
- 'play',
140
- 'playing',
141
- 'pause',
142
- 'ended',
143
- 'waiting',
144
- 'error',
145
- ]) {
146
- audio.addEventListener(event, () => {
147
- if (event === 'play') {
148
- state = 'loading'
149
- } else if (event === 'playing') {
150
- state = 'playing'
151
- } else if (event === 'pause' && state !== 'ended' && state !== 'waiting') {
152
- state = 'paused'
153
- } else if (event === 'ended') {
154
- state = 'ended'
155
- void advance(1)
156
- return
157
- } else if (event === 'error') {
158
- state = 'error'
159
- error = new Error('Audio playback failed')
160
- } else if (event === 'waiting') {
161
- state = 'loading'
162
- }
163
-
164
- emit()
165
- })
166
- }
167
-
168
- const play = async () => {
169
- if (!disposed && current()) {
170
- await audio.play()
171
- }
172
- }
173
- const pause = async () => {
174
- waitingToResume = false
175
- audio.pause()
176
- if (state === 'waiting') {
177
- state = 'paused'
178
- emit()
179
- }
180
- }
181
-
182
- return {
183
- capabilities: (): AudioCapabilities => ({
184
- supported: true,
185
- backgroundPlayback: false,
186
- systemControls: typeof navigator !== 'undefined' && 'mediaSession' in navigator,
187
- userGestureRequired: true,
188
- interruptions: false,
189
- reason:
190
- 'Background playback and OS interruption handling are unavailable on web; autoplay may require a user gesture.',
191
- }),
192
- snapshot,
193
- subscribe: (listener) => {
194
- listeners.add(listener)
195
- listener(snapshot())
196
- return () => listeners.delete(listener)
197
- },
198
- setQueue: async (tracks, startAt = 0, options = {}) => {
199
- if (disposed) {
200
- throw new Error('AudioPlayer is disposed')
201
- }
202
-
203
- queue = copyQueue(tracks)
204
- queueComplete = options.complete ?? true
205
- waitingToResume = false
206
- index = queue.length
207
- ? Math.min(
208
- Math.max(Number.isFinite(startAt) ? Math.floor(startAt) : 0, 0),
209
- queue.length - 1,
210
- )
211
- : -1
212
-
213
- error = undefined
214
- setTrack()
215
- },
216
- play,
217
- pause,
218
- seek: async (seconds) => {
219
- if (Number.isFinite(seconds)) {
220
- audio.currentTime = Math.max(0, seconds)
221
- }
222
- },
223
-
224
- updateQueue: async (tracks, options = {}) => {
225
- if (disposed) {
226
- throw new Error('AudioPlayer is disposed')
227
- }
228
- const next = copyQueue(tracks)
229
- const old = current()
230
- const at = old ? next.findIndex((t) => t.id === old.id && t.source === old.source) : -1
231
- queue = next
232
- queueComplete = options.complete ?? queueComplete
233
- if (at < 0) {
234
- waitingToResume = false
235
- index = next.length ? 0 : -1
236
- audio.pause()
237
- setTrack()
238
- if (next.length) {
239
- state = 'paused'
240
- emit()
241
- }
242
- } else {
243
- index = at
244
- if (state === 'waiting' && waitingToResume && index + 1 < queue.length) {
245
- waitingToResume = false
246
- await advance(1)
247
- } else if (state === 'waiting' && queueComplete) {
248
- state = 'ended'
249
- waitingToResume = false
250
- }
251
-
252
- updateMetadata()
253
- emit()
254
- }
255
- },
256
- setPlaybackRate: async (rate) => {
257
- if (disposed) {
258
- throw new Error('AudioPlayer is disposed')
259
- }
260
- playbackRate = bounded(rate, 0.5, 3)
261
- audio.preservesPitch = true
262
- audio.playbackRate = playbackRate
263
- emit()
264
- },
265
- setVolume: async (gain) => {
266
- if (disposed) {
267
- throw new Error('AudioPlayer is disposed')
268
- }
269
- volume = bounded(gain, 0, 1)
270
- audio.volume = volume
271
- emit()
272
- },
273
- setMuted: async (value) => {
274
- if (disposed) {
275
- throw new Error('AudioPlayer is disposed')
276
- }
277
- muted = value
278
- audio.muted = muted
279
- emit()
280
- },
281
- dispose: () => {
282
- disposed = true
283
- generation++
284
- audio.pause()
285
- audio.removeAttribute('src')
286
- audio.load()
287
- listeners.clear()
288
- queue = []
289
- if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
290
- navigator.mediaSession.metadata = null
291
- for (const action of ['play', 'pause', 'seekto', 'nexttrack', 'previoustrack'] as const) {
292
- navigator.mediaSession.setActionHandler(action, null)
293
- }
294
- }
295
- },
296
- }
7
+ const audio = new Audio()
8
+ const listeners = new Set<(value: AudioSnapshot) => void>()
9
+ let queue: Track[] = []
10
+ let index = -1
11
+ let state: AudioSnapshot['state'] = 'idle'
12
+ let error: Error | undefined
13
+ let disposed = false
14
+ let generation = 0
15
+ let playbackRate = 1
16
+ let volume = 1
17
+ let muted = false
18
+ let queueComplete = true
19
+ let waitingToResume = false
20
+ const current = () => queue[index]
21
+ const snapshot = (): AudioSnapshot => ({
22
+ state,
23
+ playbackRate,
24
+ volume,
25
+ muted,
26
+ queueComplete,
27
+ track: current(),
28
+ currentTime: audio.currentTime || 0,
29
+ duration: Number.isFinite(audio.duration) ? audio.duration : 0,
30
+ error,
31
+ })
32
+
33
+ const emit = () => {
34
+ const value = snapshot()
35
+ const ownGeneration = generation
36
+
37
+ for (const listener of listeners) {
38
+ if (disposed || ownGeneration !== generation) {
39
+ break
40
+ }
41
+
42
+ listener(value)
43
+ }
44
+ }
45
+
46
+ const updateMetadata = () => {
47
+ const track = current()
48
+
49
+ if (!track) {
50
+ if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
51
+ navigator.mediaSession.metadata = null
52
+ }
53
+
54
+ return
55
+ }
56
+
57
+ if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
58
+ navigator.mediaSession.metadata = new MediaMetadata({
59
+ title: track.title ?? track.id,
60
+ artist: track.artist ?? '',
61
+ album: track.album ?? '',
62
+ })
63
+
64
+ navigator.mediaSession.setActionHandler('play', () => {
65
+ void play().catch(() => {})
66
+ })
67
+
68
+ navigator.mediaSession.setActionHandler('pause', () => {
69
+ void pause()
70
+ })
71
+
72
+ navigator.mediaSession.setActionHandler('seekto', (event) => {
73
+ if (event.seekTime != null) {
74
+ audio.currentTime = event.seekTime
75
+ }
76
+ })
77
+
78
+ navigator.mediaSession.setActionHandler('nexttrack', () => {
79
+ void advance(1)
80
+ })
81
+
82
+ navigator.mediaSession.setActionHandler('previoustrack', () => {
83
+ void advance(-1)
84
+ })
85
+ }
86
+ }
87
+
88
+ const setTrack = () => {
89
+ generation++
90
+ error = undefined
91
+
92
+ const track = current()
93
+
94
+ if (!track) {
95
+ audio.removeAttribute('src')
96
+ state = 'idle'
97
+ updateMetadata()
98
+ emit()
99
+ return
100
+ }
101
+
102
+ audio.src = track.source
103
+ audio.playbackRate = playbackRate
104
+ audio.preservesPitch = true
105
+ audio.volume = volume
106
+ audio.muted = muted
107
+ state = 'loading'
108
+ updateMetadata()
109
+ emit()
110
+ }
111
+
112
+ const advance = async (delta: number) => {
113
+ if (!queue.length) {
114
+ return
115
+ }
116
+
117
+ if (delta > 0 && index + 1 >= queue.length) {
118
+ state = queueComplete ? 'ended' : 'waiting'
119
+ waitingToResume = !queueComplete
120
+ audio.pause()
121
+ emit()
122
+ return
123
+ }
124
+
125
+ index = Math.max(0, Math.min(index + delta, queue.length - 1))
126
+ setTrack()
127
+
128
+ const ownGeneration = generation
129
+
130
+ try {
131
+ await audio.play()
132
+ } catch (cause) {
133
+ if (disposed || ownGeneration !== generation) {
134
+ return
135
+ }
136
+
137
+ error = cause instanceof Error ? cause : new Error(String(cause))
138
+ state = 'error'
139
+ emit()
140
+ }
141
+ }
142
+
143
+ for (const event of [
144
+ 'timeupdate',
145
+ 'durationchange',
146
+ 'play',
147
+ 'playing',
148
+ 'pause',
149
+ 'ended',
150
+ 'waiting',
151
+ 'error',
152
+ ]) {
153
+ audio.addEventListener(event, () => {
154
+ if (event === 'play') {
155
+ state = 'loading'
156
+ } else if (event === 'playing') {
157
+ state = 'playing'
158
+ } else if (event === 'pause' && state !== 'ended' && state !== 'waiting') {
159
+ state = 'paused'
160
+ } else if (event === 'ended') {
161
+ state = 'ended'
162
+ void advance(1)
163
+ return
164
+ } else if (event === 'error') {
165
+ state = 'error'
166
+ error = new Error('Audio playback failed')
167
+ } else if (event === 'waiting') {
168
+ state = 'loading'
169
+ }
170
+
171
+ emit()
172
+ })
173
+ }
174
+
175
+ const play = async () => {
176
+ if (!disposed && current()) {
177
+ await audio.play()
178
+ }
179
+ }
180
+
181
+ const pause = async () => {
182
+ waitingToResume = false
183
+ audio.pause()
184
+ if (state === 'waiting') {
185
+ state = 'paused'
186
+ emit()
187
+ }
188
+ }
189
+
190
+ return {
191
+ capabilities: (): AudioCapabilities => ({
192
+ supported: true,
193
+ backgroundPlayback: false,
194
+ systemControls: typeof navigator !== 'undefined' && 'mediaSession' in navigator,
195
+ userGestureRequired: true,
196
+ interruptions: false,
197
+ reason:
198
+ 'Background playback and OS interruption handling are unavailable on web; autoplay may require a user gesture.',
199
+ }),
200
+ snapshot,
201
+ subscribe: (listener) => {
202
+ listeners.add(listener)
203
+ listener(snapshot())
204
+ return () => listeners.delete(listener)
205
+ },
206
+ setQueue: async (tracks, startAt = 0, options = {}) => {
207
+ if (disposed) {
208
+ throw new Error('AudioPlayer is disposed')
209
+ }
210
+
211
+ queue = copyQueue(tracks)
212
+ queueComplete = options.complete ?? true
213
+ waitingToResume = false
214
+ index = queue.length
215
+ ? Math.min(
216
+ Math.max(Number.isFinite(startAt) ? Math.floor(startAt) : 0, 0),
217
+ queue.length - 1,
218
+ )
219
+ : -1
220
+
221
+ error = undefined
222
+ setTrack()
223
+ },
224
+ play,
225
+ pause,
226
+ seek: async (seconds) => {
227
+ if (Number.isFinite(seconds)) {
228
+ audio.currentTime = Math.max(0, seconds)
229
+ }
230
+ },
231
+
232
+ updateQueue: async (tracks, options = {}) => {
233
+ if (disposed) {
234
+ throw new Error('AudioPlayer is disposed')
235
+ }
236
+
237
+ const next = copyQueue(tracks)
238
+ const old = current()
239
+ const at = old ? next.findIndex((t) => t.id === old.id && t.source === old.source) : -1
240
+
241
+ queue = next
242
+ queueComplete = options.complete ?? queueComplete
243
+ if (at < 0) {
244
+ waitingToResume = false
245
+ index = next.length ? 0 : -1
246
+ audio.pause()
247
+ setTrack()
248
+ if (next.length) {
249
+ state = 'paused'
250
+ emit()
251
+ }
252
+ } else {
253
+ index = at
254
+ if (state === 'waiting' && waitingToResume && index + 1 < queue.length) {
255
+ waitingToResume = false
256
+ await advance(1)
257
+ } else if (state === 'waiting' && queueComplete) {
258
+ state = 'ended'
259
+ waitingToResume = false
260
+ }
261
+
262
+ updateMetadata()
263
+ emit()
264
+ }
265
+ },
266
+ setPlaybackRate: async (rate) => {
267
+ if (disposed) {
268
+ throw new Error('AudioPlayer is disposed')
269
+ }
270
+
271
+ playbackRate = bounded(rate, 0.5, 3)
272
+ audio.preservesPitch = true
273
+ audio.playbackRate = playbackRate
274
+ emit()
275
+ },
276
+ setVolume: async (gain) => {
277
+ if (disposed) {
278
+ throw new Error('AudioPlayer is disposed')
279
+ }
280
+
281
+ volume = bounded(gain, 0, 1)
282
+ audio.volume = volume
283
+ emit()
284
+ },
285
+ setMuted: async (value) => {
286
+ if (disposed) {
287
+ throw new Error('AudioPlayer is disposed')
288
+ }
289
+
290
+ muted = value
291
+ audio.muted = muted
292
+ emit()
293
+ },
294
+ dispose: () => {
295
+ disposed = true
296
+ generation++
297
+ audio.pause()
298
+ audio.removeAttribute('src')
299
+ audio.load()
300
+ listeners.clear()
301
+ queue = []
302
+ if (typeof navigator !== 'undefined' && 'mediaSession' in navigator) {
303
+ navigator.mediaSession.metadata = null
304
+ for (const action of ['play', 'pause', 'seekto', 'nexttrack', 'previoustrack'] as const) {
305
+ navigator.mediaSession.setActionHandler(action, null)
306
+ }
307
+ }
308
+ },
309
+ }
297
310
  }
@@ -3,5 +3,5 @@ import type { AudioPlayer } from './types'
3
3
  /** Keep Windows imports independent of mobile backends; playback is unavailable. */
4
4
  /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
5
5
  export const createAudioPlayer = (): AudioPlayer => {
6
- throw new Error('@octane-xplat/audio is not available on Windows')
6
+ throw new Error('@octane-xplat/audio is not available on Windows')
7
7
  }
package/src/queue.ts CHANGED
@@ -2,12 +2,14 @@ import type { Track } from './types'
2
2
 
3
3
  /** Copy caller data and reject ambiguous identities before changing playback. */
4
4
  export function copyQueue(tracks: readonly Track[]): Track[] {
5
- const ids = new Set<string>()
6
- return tracks.map((track) => {
7
- if (!track.id || !track.source || ids.has(track.id)) {
8
- throw new Error('Audio queue requires nonempty unique IDs and sources')
9
- }
10
- ids.add(track.id)
11
- return { ...track }
12
- })
5
+ const ids = new Set<string>()
6
+
7
+ return tracks.map((track) => {
8
+ if (!track.id || !track.source || ids.has(track.id)) {
9
+ throw new Error('Audio queue requires nonempty unique IDs and sources')
10
+ }
11
+
12
+ ids.add(track.id)
13
+ return { ...track }
14
+ })
13
15
  }