@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.web.ts CHANGED
@@ -1,183 +1,310 @@
1
+ import { copyQueue } from './queue'
2
+ import { bounded } from './settings'
1
3
  import type { AudioCapabilities, AudioPlayer, AudioSnapshot, Track } from './types'
2
4
 
5
+ /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
3
6
  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
- }
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
+ }
183
310
  }
@@ -0,0 +1,7 @@
1
+ import type { AudioPlayer } from './types'
2
+
3
+ /** Keep Windows imports independent of mobile backends; playback is unavailable. */
4
+ /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
5
+ export const createAudioPlayer = (): AudioPlayer => {
6
+ throw new Error('@octane-xplat/audio is not available on Windows')
7
+ }
package/src/queue.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { Track } from './types'
2
+
3
+ /** Copy caller data and reject ambiguous identities before changing playback. */
4
+ export function copyQueue(tracks: readonly Track[]): Track[] {
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
+ })
15
+ }
@@ -0,0 +1,8 @@
1
+ /** Internal validation shared by the platform leaves. */
2
+ export function bounded(value: number, min: number, max: number): number {
3
+ if (!Number.isFinite(value)) {
4
+ throw new RangeError('Audio setting must be finite')
5
+ }
6
+
7
+ return Math.max(min, Math.min(max, value))
8
+ }
package/src/types.ts CHANGED
@@ -1,41 +1,103 @@
1
+ /** One playable local path or HTTP(S) source with a stable app-owned identity. */
1
2
  export type Track = {
2
- id: string
3
- source: string
4
- title?: string
5
- artist?: string
6
- album?: string
3
+ /** App-owned stable identity — queue operations key on it. */
4
+ id: string
5
+ /** Local file path or HTTP(S) URL. */
6
+ source: string
7
+ /** Display title for system controls/lock screen. */
8
+ title?: string
9
+ /** Display artist for system controls. */
10
+ artist?: string
11
+ /** Display album for system controls. */
12
+ album?: string
7
13
  }
8
14
 
15
+ /** Availability of playback and OS integration on this host. */
9
16
  export type AudioCapabilities = {
10
- supported: boolean
11
- backgroundPlayback: boolean
12
- systemControls: boolean
13
- userGestureRequired: boolean
14
- interruptions: boolean
15
- reason?: string
17
+ /** Any playback path exists on this host. */
18
+ supported: boolean
19
+ /** Playback can continue when the app is backgrounded/screen-locked. */
20
+ backgroundPlayback: boolean
21
+ /** Lock screen / control-center / media-key integration is available. */
22
+ systemControls: boolean
23
+ /** The first play() must be called from a user gesture (web autoplay policy). */
24
+ userGestureRequired: boolean
25
+ /** The host delivers audio-interruption events (calls, Siri, other apps). */
26
+ interruptions: boolean
27
+ /** Why supported is false, when known. */
28
+ reason?: string
16
29
  }
17
30
 
18
- export type PlaybackState = 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'error'
31
+ /** Observable loading, playback, and terminal state. */
32
+ export type PlaybackState =
33
+ | 'idle'
34
+ | 'loading'
35
+ | 'playing'
36
+ | 'paused'
37
+ | 'waiting'
38
+ | 'ended'
39
+ | 'error'
19
40
 
41
+ /** Whether a queue may receive more items. */
42
+ export interface QueueOptions {
43
+ /** Defaults to true for setQueue; updateQueue retains the current value. */
44
+ complete?: boolean
45
+ }
46
+
47
+ /** Current playback position (seconds) and persistent player settings. */
20
48
  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
49
+ /** Current observable playback state. */
50
+ state: PlaybackState
51
+ /** The queue item being played, undefined in 'idle'. */
52
+ track?: Track
53
+ /** Current position in seconds. */
54
+ currentTime: number
55
+ /** Track length in seconds, or 0 until known. */
56
+ duration: number
57
+ /** The failure behind state === 'error'. */
58
+ error?: Error
59
+ /** Requested speed, 0.5–3; defaults to 1. Pitch is preserved. */
60
+ playbackRate: number
61
+ /** Remembered gain, 0–1; defaults to 1. Independent of mute. */
62
+ volume: number
63
+ /** Whether output is muted; defaults to false. */
64
+ muted: boolean
65
+ /** False while more items may arrive; exhaustion then reports waiting. */
66
+ queueComplete: boolean
28
67
  }
29
68
 
69
+ /** An owned audio queue. Dispose it when its app/service lifetime ends. */
30
70
  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
71
+ /** Inspect host availability before offering OS integrations. */
72
+ capabilities(): AudioCapabilities
73
+ /** Read current seconds and requested settings. */
74
+ snapshot(): AudioSnapshot
75
+ /** Observe immediately and on changes; returns an unsubscribe function. */
76
+ subscribe(listener: (snapshot: AudioSnapshot) => void): () => void
77
+ /** Replace the queue and prepare the clamped zero-based start index, paused. */
78
+ setQueue(tracks: readonly Track[], startAt?: number, options?: QueueOptions): Promise<void>
79
+ /**
80
+ * Replace queue metadata/future items, retaining the current ID+source without
81
+ * reloading it. Removing/replacing it selects the first new item paused.
82
+ * Appending while waiting resumes only if playback was not explicitly paused.
83
+ * Duplicate/empty IDs or sources reject before changing the queue.
84
+ */
85
+ updateQueue(tracks: readonly Track[], options?: QueueOptions): Promise<void>
86
+ /** Begin/resume playback; browser autoplay restrictions may reject. */
87
+ play(): Promise<void>
88
+ /** Pause, cancelling interruption auto-resume. */
89
+ pause(): Promise<void>
90
+ /** Seek within the current item in seconds; nonfinite values are ignored. */
91
+ seek(seconds: number): Promise<void>
92
+ /** Set pitch-preserving speed, clamped to 0.5–3. Nonfinite values reject. */
93
+ setPlaybackRate(rate: number): Promise<void>
94
+ /** Set remembered gain, clamped to 0–1. Nonfinite values reject. */
95
+ setVolume(volume: number): Promise<void>
96
+ /** Mute without changing remembered volume. */
97
+ setMuted(muted: boolean): Promise<void>
98
+ /** Release resources. Repeated disposal is safe. */
99
+ dispose(): void
39
100
  }
40
101
 
102
+ /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
41
103
  export declare function createAudioPlayer(): AudioPlayer
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ "audio.android.d.ts",
5
+ "audio.d.ts",
6
+ "audio.ios.d.ts",
7
+ "index.d.ts",
8
+ "queue.d.ts",
9
+ "settings.d.ts",
10
+ "types.d.ts"
11
+ ]
12
+ }
@@ -0,0 +1,3 @@
1
+ import type { AudioPlayer } from './types.js';
2
+ /** Create an independent player on web/iOS/macOS; Android owns one app playback service. */
3
+ export declare const createAudioPlayer: () => AudioPlayer;