audio-channel-queue 1.9.0 → 1.10.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/README.md +197 -313
- package/dist/core.d.ts +59 -1
- package/dist/core.js +331 -40
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +10 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +21 -2
- package/dist/info.d.ts +17 -6
- package/dist/info.js +81 -10
- package/dist/pause.js +1 -1
- package/dist/queue-manipulation.d.ts +104 -0
- package/dist/queue-manipulation.js +319 -0
- package/dist/types.d.ts +46 -8
- package/dist/types.js +13 -1
- package/dist/utils.d.ts +25 -0
- package/dist/utils.js +98 -10
- package/dist/volume.d.ts +14 -1
- package/dist/volume.js +173 -54
- package/package.json +12 -2
- package/src/core.ts +389 -50
- package/src/errors.ts +14 -2
- package/src/index.ts +26 -5
- package/src/info.ts +107 -9
- package/src/pause.ts +4 -6
- package/src/queue-manipulation.ts +378 -0
- package/src/types.ts +51 -9
- package/src/utils.ts +110 -9
- package/src/volume.ts +214 -62
package/src/core.ts
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* @fileoverview Core queue management functions for the audio-channel-queue package
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { ExtendedAudioQueueChannel, AudioQueueOptions } from './types';
|
|
5
|
+
import { ExtendedAudioQueueChannel, AudioQueueOptions, MAX_CHANNELS, QueueConfig } from './types';
|
|
6
6
|
import { audioChannels } from './info';
|
|
7
|
-
import { extractFileName } from './utils';
|
|
7
|
+
import { extractFileName, validateAudioUrl } from './utils';
|
|
8
8
|
import {
|
|
9
9
|
emitQueueChange,
|
|
10
10
|
emitAudioStart,
|
|
@@ -12,21 +12,227 @@ import {
|
|
|
12
12
|
setupProgressTracking,
|
|
13
13
|
cleanupProgressTracking
|
|
14
14
|
} from './events';
|
|
15
|
-
import { applyVolumeDucking, restoreVolumeLevels } from './volume';
|
|
15
|
+
import { applyVolumeDucking, restoreVolumeLevels, cancelVolumeTransition } from './volume';
|
|
16
16
|
import { setupAudioErrorHandling, handleAudioError } from './errors';
|
|
17
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Global queue configuration
|
|
20
|
+
*/
|
|
21
|
+
let globalQueueConfig: QueueConfig = {
|
|
22
|
+
defaultMaxQueueSize: undefined, // unlimited by default
|
|
23
|
+
dropOldestWhenFull: false,
|
|
24
|
+
showQueueWarnings: true
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Operation lock timeout in milliseconds
|
|
29
|
+
*/
|
|
30
|
+
const OPERATION_LOCK_TIMEOUT: number = 100;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Acquires an operation lock for a channel to prevent race conditions
|
|
34
|
+
* @param channelNumber - The channel number to lock
|
|
35
|
+
* @param operationName - Name of the operation for debugging
|
|
36
|
+
* @returns Promise that resolves when lock is acquired
|
|
37
|
+
* @internal
|
|
38
|
+
*/
|
|
39
|
+
const acquireChannelLock = async (channelNumber: number, operationName: string): Promise<void> => {
|
|
40
|
+
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
41
|
+
if (!channel) return;
|
|
42
|
+
|
|
43
|
+
const startTime: number = Date.now();
|
|
44
|
+
|
|
45
|
+
// Wait for any existing lock to be released
|
|
46
|
+
while (channel.isLocked) {
|
|
47
|
+
// Prevent infinite waiting with timeout
|
|
48
|
+
if (Date.now() - startTime > OPERATION_LOCK_TIMEOUT) {
|
|
49
|
+
// eslint-disable-next-line no-console
|
|
50
|
+
console.warn(
|
|
51
|
+
`Operation lock timeout for channel ${channelNumber} during ${operationName}. ` +
|
|
52
|
+
`Forcibly acquiring lock.`
|
|
53
|
+
);
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Small delay to prevent tight polling
|
|
58
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
channel.isLocked = true;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Releases an operation lock for a channel
|
|
66
|
+
* @param channelNumber - The channel number to unlock
|
|
67
|
+
* @internal
|
|
68
|
+
*/
|
|
69
|
+
const releaseChannelLock = (channelNumber: number): void => {
|
|
70
|
+
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
71
|
+
if (channel) {
|
|
72
|
+
channel.isLocked = false;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Executes an operation with channel lock protection
|
|
78
|
+
* @param channelNumber - The channel number to operate on
|
|
79
|
+
* @param operationName - Name of the operation for debugging
|
|
80
|
+
* @param operation - The operation to execute
|
|
81
|
+
* @returns Promise that resolves with the operation result
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
const withChannelLock = async <T>(
|
|
85
|
+
channelNumber: number,
|
|
86
|
+
operationName: string,
|
|
87
|
+
operation: () => Promise<T>
|
|
88
|
+
): Promise<T> => {
|
|
89
|
+
try {
|
|
90
|
+
await acquireChannelLock(channelNumber, operationName);
|
|
91
|
+
return await operation();
|
|
92
|
+
} finally {
|
|
93
|
+
releaseChannelLock(channelNumber);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Sets the global queue configuration
|
|
99
|
+
* @param config - Queue configuration options
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* setQueueConfig({
|
|
103
|
+
* defaultMaxQueueSize: 50,
|
|
104
|
+
* dropOldestWhenFull: true,
|
|
105
|
+
* showQueueWarnings: true
|
|
106
|
+
* });
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
export const setQueueConfig = (config: Partial<QueueConfig>): void => {
|
|
110
|
+
globalQueueConfig = { ...globalQueueConfig, ...config };
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Gets the current global queue configuration
|
|
115
|
+
* @returns Current queue configuration
|
|
116
|
+
* @example
|
|
117
|
+
* ```typescript
|
|
118
|
+
* const config = getQueueConfig();
|
|
119
|
+
* console.log(`Default max queue size: ${config.defaultMaxQueueSize}`);
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export const getQueueConfig = (): QueueConfig => {
|
|
123
|
+
return { ...globalQueueConfig };
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Sets the maximum queue size for a specific channel
|
|
128
|
+
* @param channelNumber - The channel number to configure
|
|
129
|
+
* @param maxSize - Maximum queue size (undefined for unlimited)
|
|
130
|
+
* @throws Error if the channel number exceeds the maximum allowed channels
|
|
131
|
+
* @example
|
|
132
|
+
* ```typescript
|
|
133
|
+
* setChannelQueueLimit(0, 25); // Limit channel 0 to 25 items
|
|
134
|
+
* setChannelQueueLimit(1, undefined); // Remove limit for channel 1
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
export const setChannelQueueLimit = (channelNumber: number, maxSize?: number): void => {
|
|
138
|
+
// Validate channel number limits BEFORE creating any channels
|
|
139
|
+
if (channelNumber < 0) {
|
|
140
|
+
throw new Error('Channel number must be non-negative');
|
|
141
|
+
}
|
|
142
|
+
if (channelNumber >= MAX_CHANNELS) {
|
|
143
|
+
throw new Error(
|
|
144
|
+
`Channel number ${channelNumber} exceeds maximum allowed channels (${MAX_CHANNELS})`
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Ensure channel exists (now safe because we validated the limit above)
|
|
149
|
+
while (audioChannels.length <= channelNumber) {
|
|
150
|
+
audioChannels.push({
|
|
151
|
+
audioCompleteCallbacks: new Set(),
|
|
152
|
+
audioErrorCallbacks: new Set(),
|
|
153
|
+
audioPauseCallbacks: new Set(),
|
|
154
|
+
audioResumeCallbacks: new Set(),
|
|
155
|
+
audioStartCallbacks: new Set(),
|
|
156
|
+
isPaused: false,
|
|
157
|
+
progressCallbacks: new Map(),
|
|
158
|
+
queue: [],
|
|
159
|
+
queueChangeCallbacks: new Set(),
|
|
160
|
+
volume: 1.0
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
165
|
+
channel.maxQueueSize = maxSize;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Checks if adding an item to the queue would exceed limits and handles the situation
|
|
170
|
+
* @param channel - The channel to check
|
|
171
|
+
* @param channelNumber - The channel number for logging
|
|
172
|
+
* @param maxQueueSize - Override max queue size from options
|
|
173
|
+
* @returns true if the item can be added, false otherwise
|
|
174
|
+
* @internal
|
|
175
|
+
*/
|
|
176
|
+
const checkQueueLimit = (
|
|
177
|
+
channel: ExtendedAudioQueueChannel,
|
|
178
|
+
channelNumber: number,
|
|
179
|
+
maxQueueSize?: number
|
|
180
|
+
): boolean => {
|
|
181
|
+
// Determine the effective queue limit
|
|
182
|
+
const effectiveLimit =
|
|
183
|
+
maxQueueSize ?? channel.maxQueueSize ?? globalQueueConfig.defaultMaxQueueSize;
|
|
184
|
+
|
|
185
|
+
if (effectiveLimit === undefined) {
|
|
186
|
+
return true; // No limit set
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (channel.queue.length < effectiveLimit) {
|
|
190
|
+
return true; // Within limits
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Queue is at or over the limit
|
|
194
|
+
if (globalQueueConfig.showQueueWarnings) {
|
|
195
|
+
// eslint-disable-next-line no-console
|
|
196
|
+
console.warn(
|
|
197
|
+
`Queue limit reached for channel ${channelNumber}. ` +
|
|
198
|
+
`Current size: ${channel.queue.length}, Limit: ${effectiveLimit}`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (globalQueueConfig.dropOldestWhenFull) {
|
|
203
|
+
// Remove oldest item (but not currently playing)
|
|
204
|
+
if (channel.queue.length > 1) {
|
|
205
|
+
const removedAudio = channel.queue.splice(1, 1)[0];
|
|
206
|
+
cleanupProgressTracking(removedAudio, channelNumber, audioChannels);
|
|
207
|
+
|
|
208
|
+
if (globalQueueConfig.showQueueWarnings) {
|
|
209
|
+
// eslint-disable-next-line no-console
|
|
210
|
+
console.info(`Dropped oldest queued item to make room for new audio`);
|
|
211
|
+
}
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Cannot add - queue is full and not dropping oldest
|
|
217
|
+
return false;
|
|
218
|
+
};
|
|
219
|
+
|
|
18
220
|
/**
|
|
19
221
|
* Queues an audio file to a specific channel and starts playing if it's the first in queue
|
|
20
222
|
* @param audioUrl - The URL of the audio file to queue
|
|
21
223
|
* @param channelNumber - The channel number to queue the audio to (defaults to 0)
|
|
22
224
|
* @param options - Optional configuration for the audio file
|
|
23
225
|
* @returns Promise that resolves when the audio is queued and starts playing (if first in queue)
|
|
226
|
+
* @throws Error if the audio URL is invalid or potentially malicious
|
|
227
|
+
* @throws Error if the channel number exceeds the maximum allowed channels
|
|
228
|
+
* @throws Error if the queue size limit would be exceeded
|
|
24
229
|
* @example
|
|
25
230
|
* ```typescript
|
|
26
231
|
* await queueAudio('https://example.com/song.mp3', 0);
|
|
27
232
|
* await queueAudio('./sounds/notification.wav'); // Uses default channel 0
|
|
28
233
|
* await queueAudio('./music/loop.mp3', 1, { loop: true }); // Loop the audio
|
|
29
234
|
* await queueAudio('./urgent.wav', 0, { addToFront: true }); // Add to front of queue
|
|
235
|
+
* await queueAudio('./limited.mp3', 0, { maxQueueSize: 10 }); // Limit this queue to 10 items
|
|
30
236
|
* ```
|
|
31
237
|
*/
|
|
32
238
|
export const queueAudio = async (
|
|
@@ -34,6 +240,19 @@ export const queueAudio = async (
|
|
|
34
240
|
channelNumber: number = 0,
|
|
35
241
|
options?: AudioQueueOptions
|
|
36
242
|
): Promise<void> => {
|
|
243
|
+
// Validate the URL for security
|
|
244
|
+
const validatedUrl: string = validateAudioUrl(audioUrl);
|
|
245
|
+
|
|
246
|
+
// Check channel number limits
|
|
247
|
+
if (channelNumber < 0) {
|
|
248
|
+
throw new Error('Channel number must be non-negative');
|
|
249
|
+
}
|
|
250
|
+
if (channelNumber >= MAX_CHANNELS) {
|
|
251
|
+
throw new Error(
|
|
252
|
+
`Channel number ${channelNumber} exceeds maximum allowed channels (${MAX_CHANNELS})`
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
|
|
37
256
|
// Ensure the channel exists
|
|
38
257
|
while (audioChannels.length <= channelNumber) {
|
|
39
258
|
audioChannels.push({
|
|
@@ -51,11 +270,17 @@ export const queueAudio = async (
|
|
|
51
270
|
}
|
|
52
271
|
|
|
53
272
|
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
54
|
-
|
|
273
|
+
|
|
274
|
+
// Check queue size limits before creating audio element
|
|
275
|
+
if (!checkQueueLimit(channel, channelNumber, options?.maxQueueSize)) {
|
|
276
|
+
throw new Error(`Queue size limit exceeded for channel ${channelNumber}`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const audio: HTMLAudioElement = new Audio(validatedUrl);
|
|
55
280
|
|
|
56
281
|
// Set up comprehensive error handling
|
|
57
|
-
setupAudioErrorHandling(audio, channelNumber,
|
|
58
|
-
await handleAudioError(audio, channelNumber,
|
|
282
|
+
setupAudioErrorHandling(audio, channelNumber, validatedUrl, async (error: Error) => {
|
|
283
|
+
await handleAudioError(audio, channelNumber, validatedUrl, error);
|
|
59
284
|
});
|
|
60
285
|
|
|
61
286
|
// Apply options if provided
|
|
@@ -69,6 +294,10 @@ export const queueAudio = async (
|
|
|
69
294
|
// Set channel volume to match the audio volume
|
|
70
295
|
channel.volume = clampedVolume;
|
|
71
296
|
}
|
|
297
|
+
// Set channel-specific queue limit if provided
|
|
298
|
+
if (typeof options.maxQueueSize === 'number') {
|
|
299
|
+
channel.maxQueueSize = options.maxQueueSize;
|
|
300
|
+
}
|
|
72
301
|
}
|
|
73
302
|
|
|
74
303
|
// Handle priority option (same as addToFront for backward compatibility)
|
|
@@ -94,7 +323,7 @@ export const queueAudio = async (
|
|
|
94
323
|
// Use setTimeout to ensure the queue change event is emitted first
|
|
95
324
|
setTimeout(() => {
|
|
96
325
|
playAudioQueue(channelNumber).catch((error: Error) => {
|
|
97
|
-
handleAudioError(audio, channelNumber,
|
|
326
|
+
handleAudioError(audio, channelNumber, validatedUrl, error);
|
|
98
327
|
});
|
|
99
328
|
}, 0);
|
|
100
329
|
}
|
|
@@ -195,19 +424,9 @@ export const playAudioQueue = async (channelNumber: number): Promise<void> => {
|
|
|
195
424
|
audioChannels
|
|
196
425
|
);
|
|
197
426
|
|
|
198
|
-
// Restore volume levels when priority channel stops
|
|
199
|
-
await restoreVolumeLevels(channelNumber);
|
|
200
|
-
|
|
201
|
-
// Clean up event listeners
|
|
202
|
-
currentAudio.removeEventListener('loadedmetadata', handleLoadedMetadata);
|
|
203
|
-
currentAudio.removeEventListener('play', handlePlay);
|
|
204
|
-
currentAudio.removeEventListener('ended', handleEnded);
|
|
205
|
-
|
|
206
|
-
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
207
|
-
|
|
208
427
|
// Handle looping vs non-looping audio
|
|
209
428
|
if (currentAudio.loop) {
|
|
210
|
-
// For looping audio,
|
|
429
|
+
// For looping audio, keep in queue and try to restart playback
|
|
211
430
|
currentAudio.currentTime = 0;
|
|
212
431
|
try {
|
|
213
432
|
await currentAudio.play();
|
|
@@ -217,11 +436,17 @@ export const playAudioQueue = async (channelNumber: number): Promise<void> => {
|
|
|
217
436
|
resolve();
|
|
218
437
|
} else {
|
|
219
438
|
// For non-looping audio, remove from queue and play next
|
|
439
|
+
currentAudio.pause();
|
|
440
|
+
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
220
441
|
channel.queue.shift();
|
|
442
|
+
channel.isPaused = false; // Reset pause state
|
|
221
443
|
|
|
222
|
-
//
|
|
223
|
-
|
|
444
|
+
// Restore volume levels AFTER removing audio from queue
|
|
445
|
+
await restoreVolumeLevels(channelNumber);
|
|
224
446
|
|
|
447
|
+
emitQueueChange(channelNumber, audioChannels);
|
|
448
|
+
|
|
449
|
+
// Play next audio immediately if there's more in queue
|
|
225
450
|
await playAudioQueue(channelNumber);
|
|
226
451
|
resolve();
|
|
227
452
|
}
|
|
@@ -270,19 +495,21 @@ export const stopCurrentAudioInChannel = async (channelNumber: number = 0): Prom
|
|
|
270
495
|
audioChannels
|
|
271
496
|
);
|
|
272
497
|
|
|
273
|
-
// Restore volume levels when stopping
|
|
274
|
-
await restoreVolumeLevels(channelNumber);
|
|
275
|
-
|
|
276
498
|
currentAudio.pause();
|
|
277
499
|
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
278
500
|
channel.queue.shift();
|
|
279
501
|
channel.isPaused = false; // Reset pause state
|
|
280
502
|
|
|
503
|
+
// Restore volume levels AFTER removing from queue (so queue.length check works correctly)
|
|
504
|
+
await restoreVolumeLevels(channelNumber);
|
|
505
|
+
|
|
281
506
|
emitQueueChange(channelNumber, audioChannels);
|
|
282
507
|
|
|
283
|
-
// Start next audio
|
|
284
|
-
|
|
285
|
-
|
|
508
|
+
// Start next audio immediately if there's more in queue
|
|
509
|
+
if (channel.queue.length > 0) {
|
|
510
|
+
// eslint-disable-next-line no-console
|
|
511
|
+
playAudioQueue(channelNumber).catch(console.error);
|
|
512
|
+
}
|
|
286
513
|
}
|
|
287
514
|
};
|
|
288
515
|
|
|
@@ -296,35 +523,39 @@ export const stopCurrentAudioInChannel = async (channelNumber: number = 0): Prom
|
|
|
296
523
|
* ```
|
|
297
524
|
*/
|
|
298
525
|
export const stopAllAudioInChannel = async (channelNumber: number = 0): Promise<void> => {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
if (channel
|
|
302
|
-
|
|
526
|
+
return withChannelLock(channelNumber, 'stopAllAudioInChannel', async () => {
|
|
527
|
+
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
528
|
+
if (channel) {
|
|
529
|
+
if (channel.queue.length > 0) {
|
|
530
|
+
const currentAudio: HTMLAudioElement = channel.queue[0];
|
|
303
531
|
|
|
304
|
-
|
|
305
|
-
channelNumber,
|
|
306
|
-
{
|
|
532
|
+
emitAudioComplete(
|
|
307
533
|
channelNumber,
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
534
|
+
{
|
|
535
|
+
channelNumber,
|
|
536
|
+
fileName: extractFileName(currentAudio.src),
|
|
537
|
+
remainingInQueue: 0, // Will be 0 since we're clearing the queue
|
|
538
|
+
src: currentAudio.src
|
|
539
|
+
},
|
|
540
|
+
audioChannels
|
|
541
|
+
);
|
|
314
542
|
|
|
315
|
-
|
|
316
|
-
|
|
543
|
+
// Restore volume levels when stopping
|
|
544
|
+
await restoreVolumeLevels(channelNumber);
|
|
317
545
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
546
|
+
currentAudio.pause();
|
|
547
|
+
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
548
|
+
}
|
|
549
|
+
// Clean up all progress tracking for this channel
|
|
550
|
+
channel.queue.forEach((audio) =>
|
|
551
|
+
cleanupProgressTracking(audio, channelNumber, audioChannels)
|
|
552
|
+
);
|
|
553
|
+
channel.queue = [];
|
|
554
|
+
channel.isPaused = false; // Reset pause state
|
|
325
555
|
|
|
326
|
-
|
|
327
|
-
|
|
556
|
+
emitQueueChange(channelNumber, audioChannels);
|
|
557
|
+
}
|
|
558
|
+
});
|
|
328
559
|
};
|
|
329
560
|
|
|
330
561
|
/**
|
|
@@ -341,3 +572,111 @@ export const stopAllAudio = async (): Promise<void> => {
|
|
|
341
572
|
});
|
|
342
573
|
await Promise.all(stopPromises);
|
|
343
574
|
};
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Completely destroys a channel and cleans up all associated resources
|
|
578
|
+
* This stops all audio, cancels transitions, clears callbacks, and removes the channel
|
|
579
|
+
* @param channelNumber - The channel number to destroy (defaults to 0)
|
|
580
|
+
* @example
|
|
581
|
+
* ```typescript
|
|
582
|
+
* await destroyChannel(1); // Completely removes channel 1 and cleans up resources
|
|
583
|
+
* ```
|
|
584
|
+
*/
|
|
585
|
+
export const destroyChannel = async (channelNumber: number = 0): Promise<void> => {
|
|
586
|
+
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
587
|
+
if (!channel) return;
|
|
588
|
+
|
|
589
|
+
// Comprehensive cleanup of all audio elements in the queue
|
|
590
|
+
if (channel.queue && channel.queue.length > 0) {
|
|
591
|
+
channel.queue.forEach((audio: HTMLAudioElement) => {
|
|
592
|
+
// Properly clean up each audio element
|
|
593
|
+
const cleanAudio = audio;
|
|
594
|
+
cleanAudio.pause();
|
|
595
|
+
cleanAudio.currentTime = 0;
|
|
596
|
+
|
|
597
|
+
// Remove all event listeners if possible
|
|
598
|
+
if (cleanAudio.parentNode) {
|
|
599
|
+
cleanAudio.parentNode.removeChild(cleanAudio);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Clean up audio attributes
|
|
603
|
+
cleanAudio.removeAttribute('src');
|
|
604
|
+
|
|
605
|
+
// Reset audio element state
|
|
606
|
+
if (cleanAudio.src) {
|
|
607
|
+
// Copy essential properties
|
|
608
|
+
cleanAudio.src = '';
|
|
609
|
+
try {
|
|
610
|
+
cleanAudio.load();
|
|
611
|
+
} catch {
|
|
612
|
+
// Ignore load errors in tests (jsdom limitation)
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// Stop all audio in the channel (this handles additional cleanup)
|
|
619
|
+
await stopAllAudioInChannel(channelNumber);
|
|
620
|
+
|
|
621
|
+
// Cancel any active volume transitions
|
|
622
|
+
cancelVolumeTransition(channelNumber);
|
|
623
|
+
|
|
624
|
+
// Clear all callback sets completely
|
|
625
|
+
const callbackProperties = [
|
|
626
|
+
'audioCompleteCallbacks',
|
|
627
|
+
'audioErrorCallbacks',
|
|
628
|
+
'audioPauseCallbacks',
|
|
629
|
+
'audioResumeCallbacks',
|
|
630
|
+
'audioStartCallbacks',
|
|
631
|
+
'queueChangeCallbacks',
|
|
632
|
+
'progressCallbacks'
|
|
633
|
+
] as const;
|
|
634
|
+
|
|
635
|
+
callbackProperties.forEach((prop) => {
|
|
636
|
+
if (channel[prop]) {
|
|
637
|
+
channel[prop].clear();
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
// Remove optional channel configuration
|
|
642
|
+
delete channel.fadeState;
|
|
643
|
+
delete channel.retryConfig;
|
|
644
|
+
|
|
645
|
+
// Reset required properties to clean state
|
|
646
|
+
channel.isPaused = false;
|
|
647
|
+
channel.volume = 1.0;
|
|
648
|
+
channel.queue = [];
|
|
649
|
+
|
|
650
|
+
// Remove the channel completely
|
|
651
|
+
delete audioChannels[channelNumber];
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Destroys all channels and cleans up all resources
|
|
656
|
+
* This is useful for complete cleanup when the audio system is no longer needed
|
|
657
|
+
* @example
|
|
658
|
+
* ```typescript
|
|
659
|
+
* await destroyAllChannels(); // Complete cleanup - removes all channels
|
|
660
|
+
* ```
|
|
661
|
+
*/
|
|
662
|
+
export const destroyAllChannels = async (): Promise<void> => {
|
|
663
|
+
const destroyPromises: Promise<void>[] = [];
|
|
664
|
+
|
|
665
|
+
// Collect indices of existing channels
|
|
666
|
+
const channelIndices: number[] = [];
|
|
667
|
+
audioChannels.forEach((_channel: ExtendedAudioQueueChannel, index: number) => {
|
|
668
|
+
if (audioChannels[index]) {
|
|
669
|
+
channelIndices.push(index);
|
|
670
|
+
}
|
|
671
|
+
});
|
|
672
|
+
|
|
673
|
+
// Destroy all channels in parallel
|
|
674
|
+
channelIndices.forEach((index: number) => {
|
|
675
|
+
destroyPromises.push(destroyChannel(index));
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
await Promise.all(destroyPromises);
|
|
679
|
+
|
|
680
|
+
// Clear the entire array
|
|
681
|
+
audioChannels.length = 0;
|
|
682
|
+
};
|
package/src/errors.ts
CHANGED
|
@@ -7,7 +7,8 @@ import {
|
|
|
7
7
|
AudioErrorCallback,
|
|
8
8
|
RetryConfig,
|
|
9
9
|
ErrorRecoveryOptions,
|
|
10
|
-
ExtendedAudioQueueChannel
|
|
10
|
+
ExtendedAudioQueueChannel,
|
|
11
|
+
MAX_CHANNELS
|
|
11
12
|
} from './types';
|
|
12
13
|
import { audioChannels } from './info';
|
|
13
14
|
import { extractFileName } from './utils';
|
|
@@ -37,6 +38,7 @@ const loadTimeouts: WeakMap<HTMLAudioElement, number> = new WeakMap();
|
|
|
37
38
|
* Subscribes to audio error events for a specific channel
|
|
38
39
|
* @param channelNumber - The channel number to listen to (defaults to 0)
|
|
39
40
|
* @param callback - Function to call when an audio error occurs
|
|
41
|
+
* @throws Error if the channel number exceeds the maximum allowed channels
|
|
40
42
|
* @example
|
|
41
43
|
* ```typescript
|
|
42
44
|
* onAudioError(0, (errorInfo) => {
|
|
@@ -46,7 +48,17 @@ const loadTimeouts: WeakMap<HTMLAudioElement, number> = new WeakMap();
|
|
|
46
48
|
* ```
|
|
47
49
|
*/
|
|
48
50
|
export const onAudioError = (channelNumber: number = 0, callback: AudioErrorCallback): void => {
|
|
49
|
-
//
|
|
51
|
+
// Validate channel number limits BEFORE creating any channels
|
|
52
|
+
if (channelNumber < 0) {
|
|
53
|
+
throw new Error('Channel number must be non-negative');
|
|
54
|
+
}
|
|
55
|
+
if (channelNumber >= MAX_CHANNELS) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Channel number ${channelNumber} exceeds maximum allowed channels (${MAX_CHANNELS})`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Ensure channel exists (now safe because we validated the limit above)
|
|
50
62
|
while (audioChannels.length <= channelNumber) {
|
|
51
63
|
audioChannels.push({
|
|
52
64
|
audioCompleteCallbacks: new Set(),
|
package/src/index.ts
CHANGED
|
@@ -11,9 +11,24 @@ export {
|
|
|
11
11
|
stopCurrentAudioInChannel,
|
|
12
12
|
stopAllAudioInChannel,
|
|
13
13
|
stopAllAudio,
|
|
14
|
-
playAudioQueue
|
|
14
|
+
playAudioQueue,
|
|
15
|
+
destroyChannel,
|
|
16
|
+
destroyAllChannels,
|
|
17
|
+
setQueueConfig,
|
|
18
|
+
getQueueConfig,
|
|
19
|
+
setChannelQueueLimit
|
|
15
20
|
} from './core';
|
|
16
21
|
|
|
22
|
+
// Queue manipulation functions
|
|
23
|
+
export {
|
|
24
|
+
clearQueueAfterCurrent,
|
|
25
|
+
getQueueItemInfo,
|
|
26
|
+
getQueueLength,
|
|
27
|
+
removeQueuedItem,
|
|
28
|
+
reorderQueue,
|
|
29
|
+
swapQueueItems
|
|
30
|
+
} from './queue-manipulation';
|
|
31
|
+
|
|
17
32
|
// Error handling and recovery functions
|
|
18
33
|
export {
|
|
19
34
|
getErrorRecovery,
|
|
@@ -53,7 +68,9 @@ export {
|
|
|
53
68
|
setAllChannelsVolume,
|
|
54
69
|
setChannelVolume,
|
|
55
70
|
setVolumeDucking,
|
|
56
|
-
transitionVolume
|
|
71
|
+
transitionVolume,
|
|
72
|
+
cancelVolumeTransition,
|
|
73
|
+
cancelAllVolumeTransitions
|
|
57
74
|
} from './volume';
|
|
58
75
|
|
|
59
76
|
// Audio information and progress tracking functions
|
|
@@ -81,7 +98,9 @@ export {
|
|
|
81
98
|
cleanWebpackFilename,
|
|
82
99
|
createQueueSnapshot,
|
|
83
100
|
extractFileName,
|
|
84
|
-
getAudioInfoFromElement
|
|
101
|
+
getAudioInfoFromElement,
|
|
102
|
+
sanitizeForDisplay,
|
|
103
|
+
validateAudioUrl
|
|
85
104
|
} from './utils';
|
|
86
105
|
|
|
87
106
|
// TypeScript type definitions and interfaces
|
|
@@ -103,10 +122,12 @@ export type {
|
|
|
103
122
|
ProgressCallback,
|
|
104
123
|
QueueChangeCallback,
|
|
105
124
|
QueueItem,
|
|
125
|
+
QueueManipulationResult,
|
|
106
126
|
QueueSnapshot,
|
|
107
127
|
RetryConfig,
|
|
108
|
-
VolumeConfig
|
|
128
|
+
VolumeConfig,
|
|
129
|
+
QueueConfig
|
|
109
130
|
} from './types';
|
|
110
131
|
|
|
111
132
|
// Enums and constants
|
|
112
|
-
export { EasingType, FadeType, GLOBAL_PROGRESS_KEY } from './types';
|
|
133
|
+
export { EasingType, FadeType, MAX_CHANNELS, TimerType, GLOBAL_PROGRESS_KEY } from './types';
|