audio-channel-queue 1.8.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 +333 -41
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +37 -18
- package/dist/events.js +21 -14
- package/dist/index.d.ts +9 -8
- package/dist/index.js +23 -3
- package/dist/info.d.ts +17 -6
- package/dist/info.js +89 -17
- package/dist/pause.d.ts +24 -12
- package/dist/pause.js +93 -41
- package/dist/queue-manipulation.d.ts +104 -0
- package/dist/queue-manipulation.js +319 -0
- package/dist/types.d.ts +58 -11
- package/dist/types.js +18 -1
- package/dist/utils.d.ts +25 -0
- package/dist/utils.js +102 -13
- package/dist/volume.d.ts +14 -1
- package/dist/volume.js +201 -60
- package/package.json +18 -3
- package/src/core.ts +437 -81
- package/src/errors.ts +516 -480
- package/src/events.ts +36 -27
- package/src/index.ts +68 -43
- package/src/info.ts +129 -30
- package/src/pause.ts +169 -88
- package/src/queue-manipulation.ts +378 -0
- package/src/types.ts +63 -11
- package/src/utils.ts +117 -16
- package/src/volume.ts +250 -81
package/src/core.ts
CHANGED
|
@@ -2,38 +2,257 @@
|
|
|
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';
|
|
8
|
-
import {
|
|
9
|
-
emitQueueChange,
|
|
10
|
-
emitAudioStart,
|
|
11
|
-
emitAudioComplete,
|
|
12
|
-
setupProgressTracking,
|
|
13
|
-
cleanupProgressTracking
|
|
7
|
+
import { extractFileName, validateAudioUrl } from './utils';
|
|
8
|
+
import {
|
|
9
|
+
emitQueueChange,
|
|
10
|
+
emitAudioStart,
|
|
11
|
+
emitAudioComplete,
|
|
12
|
+
setupProgressTracking,
|
|
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 (
|
|
33
|
-
audioUrl: string,
|
|
34
|
-
channelNumber: number = 0,
|
|
239
|
+
audioUrl: string,
|
|
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
|
}
|
|
@@ -114,8 +343,8 @@ export const queueAudio = async (
|
|
|
114
343
|
* ```
|
|
115
344
|
*/
|
|
116
345
|
export const queueAudioPriority = async (
|
|
117
|
-
audioUrl: string,
|
|
118
|
-
channelNumber: number = 0,
|
|
346
|
+
audioUrl: string,
|
|
347
|
+
channelNumber: number = 0,
|
|
119
348
|
options?: AudioQueueOptions
|
|
120
349
|
): Promise<void> => {
|
|
121
350
|
const priorityOptions: AudioQueueOptions = { ...options, addToFront: true };
|
|
@@ -152,17 +381,21 @@ export const playAudioQueue = async (channelNumber: number): Promise<void> => {
|
|
|
152
381
|
let hasStarted: boolean = false;
|
|
153
382
|
let metadataLoaded: boolean = false;
|
|
154
383
|
let playStarted: boolean = false;
|
|
155
|
-
|
|
384
|
+
|
|
156
385
|
// Check if we should fire onAudioStart (both conditions met)
|
|
157
386
|
const tryFireAudioStart = (): void => {
|
|
158
387
|
if (!hasStarted && metadataLoaded && playStarted) {
|
|
159
388
|
hasStarted = true;
|
|
160
|
-
emitAudioStart(
|
|
389
|
+
emitAudioStart(
|
|
161
390
|
channelNumber,
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
391
|
+
{
|
|
392
|
+
channelNumber,
|
|
393
|
+
duration: currentAudio.duration * 1000,
|
|
394
|
+
fileName: extractFileName(currentAudio.src),
|
|
395
|
+
src: currentAudio.src
|
|
396
|
+
},
|
|
397
|
+
audioChannels
|
|
398
|
+
);
|
|
166
399
|
}
|
|
167
400
|
};
|
|
168
401
|
|
|
@@ -180,26 +413,20 @@ export const playAudioQueue = async (channelNumber: number): Promise<void> => {
|
|
|
180
413
|
|
|
181
414
|
// Event handler for when audio ends
|
|
182
415
|
const handleEnded = async (): Promise<void> => {
|
|
183
|
-
emitAudioComplete(
|
|
416
|
+
emitAudioComplete(
|
|
184
417
|
channelNumber,
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
currentAudio.removeEventListener('loadedmetadata', handleLoadedMetadata);
|
|
195
|
-
currentAudio.removeEventListener('play', handlePlay);
|
|
196
|
-
currentAudio.removeEventListener('ended', handleEnded);
|
|
197
|
-
|
|
198
|
-
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
199
|
-
|
|
418
|
+
{
|
|
419
|
+
channelNumber,
|
|
420
|
+
fileName: extractFileName(currentAudio.src),
|
|
421
|
+
remainingInQueue: channel.queue.length - 1,
|
|
422
|
+
src: currentAudio.src
|
|
423
|
+
},
|
|
424
|
+
audioChannels
|
|
425
|
+
);
|
|
426
|
+
|
|
200
427
|
// Handle looping vs non-looping audio
|
|
201
428
|
if (currentAudio.loop) {
|
|
202
|
-
// For looping audio,
|
|
429
|
+
// For looping audio, keep in queue and try to restart playback
|
|
203
430
|
currentAudio.currentTime = 0;
|
|
204
431
|
try {
|
|
205
432
|
await currentAudio.play();
|
|
@@ -209,11 +436,17 @@ export const playAudioQueue = async (channelNumber: number): Promise<void> => {
|
|
|
209
436
|
resolve();
|
|
210
437
|
} else {
|
|
211
438
|
// For non-looping audio, remove from queue and play next
|
|
439
|
+
currentAudio.pause();
|
|
440
|
+
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
212
441
|
channel.queue.shift();
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
442
|
+
channel.isPaused = false; // Reset pause state
|
|
443
|
+
|
|
444
|
+
// Restore volume levels AFTER removing audio from queue
|
|
445
|
+
await restoreVolumeLevels(channelNumber);
|
|
446
|
+
|
|
447
|
+
emitQueueChange(channelNumber, audioChannels);
|
|
448
|
+
|
|
449
|
+
// Play next audio immediately if there's more in queue
|
|
217
450
|
await playAudioQueue(channelNumber);
|
|
218
451
|
resolve();
|
|
219
452
|
}
|
|
@@ -225,7 +458,7 @@ export const playAudioQueue = async (channelNumber: number): Promise<void> => {
|
|
|
225
458
|
currentAudio.addEventListener('ended', handleEnded);
|
|
226
459
|
|
|
227
460
|
// Check if metadata is already loaded (in case it loads before we add the listener)
|
|
228
|
-
if (currentAudio.readyState >= 1) {
|
|
461
|
+
if (currentAudio.readyState >= 1) {
|
|
229
462
|
metadataLoaded = true;
|
|
230
463
|
}
|
|
231
464
|
|
|
@@ -250,26 +483,33 @@ export const stopCurrentAudioInChannel = async (channelNumber: number = 0): Prom
|
|
|
250
483
|
const channel: ExtendedAudioQueueChannel = audioChannels[channelNumber];
|
|
251
484
|
if (channel && channel.queue.length > 0) {
|
|
252
485
|
const currentAudio: HTMLAudioElement = channel.queue[0];
|
|
253
|
-
|
|
254
|
-
emitAudioComplete(channelNumber, {
|
|
255
|
-
channelNumber,
|
|
256
|
-
fileName: extractFileName(currentAudio.src),
|
|
257
|
-
remainingInQueue: channel.queue.length - 1,
|
|
258
|
-
src: currentAudio.src
|
|
259
|
-
}, audioChannels);
|
|
260
486
|
|
|
261
|
-
|
|
262
|
-
|
|
487
|
+
emitAudioComplete(
|
|
488
|
+
channelNumber,
|
|
489
|
+
{
|
|
490
|
+
channelNumber,
|
|
491
|
+
fileName: extractFileName(currentAudio.src),
|
|
492
|
+
remainingInQueue: channel.queue.length - 1,
|
|
493
|
+
src: currentAudio.src
|
|
494
|
+
},
|
|
495
|
+
audioChannels
|
|
496
|
+
);
|
|
263
497
|
|
|
264
498
|
currentAudio.pause();
|
|
265
499
|
cleanupProgressTracking(currentAudio, channelNumber, audioChannels);
|
|
266
500
|
channel.queue.shift();
|
|
267
501
|
channel.isPaused = false; // Reset pause state
|
|
268
502
|
|
|
503
|
+
// Restore volume levels AFTER removing from queue (so queue.length check works correctly)
|
|
504
|
+
await restoreVolumeLevels(channelNumber);
|
|
505
|
+
|
|
269
506
|
emitQueueChange(channelNumber, audioChannels);
|
|
270
|
-
|
|
271
|
-
// Start next audio
|
|
272
|
-
|
|
507
|
+
|
|
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
|
+
}
|
|
273
513
|
}
|
|
274
514
|
};
|
|
275
515
|
|
|
@@ -283,31 +523,39 @@ export const stopCurrentAudioInChannel = async (channelNumber: number = 0): Prom
|
|
|
283
523
|
* ```
|
|
284
524
|
*/
|
|
285
525
|
export const stopAllAudioInChannel = async (channelNumber: number = 0): Promise<void> => {
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
if (channel
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
emitAudioComplete(channelNumber, {
|
|
292
|
-
channelNumber,
|
|
293
|
-
fileName: extractFileName(currentAudio.src),
|
|
294
|
-
remainingInQueue: 0, // Will be 0 since we're clearing the queue
|
|
295
|
-
src: currentAudio.src
|
|
296
|
-
}, audioChannels);
|
|
297
|
-
|
|
298
|
-
// Restore volume levels when stopping
|
|
299
|
-
await restoreVolumeLevels(channelNumber);
|
|
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];
|
|
300
531
|
|
|
301
|
-
|
|
302
|
-
|
|
532
|
+
emitAudioComplete(
|
|
533
|
+
channelNumber,
|
|
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
|
+
);
|
|
542
|
+
|
|
543
|
+
// Restore volume levels when stopping
|
|
544
|
+
await restoreVolumeLevels(channelNumber);
|
|
545
|
+
|
|
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
|
|
555
|
+
|
|
556
|
+
emitQueueChange(channelNumber, audioChannels);
|
|
303
557
|
}
|
|
304
|
-
|
|
305
|
-
channel.queue.forEach(audio => cleanupProgressTracking(audio, channelNumber, audioChannels));
|
|
306
|
-
channel.queue = [];
|
|
307
|
-
channel.isPaused = false; // Reset pause state
|
|
308
|
-
|
|
309
|
-
emitQueueChange(channelNumber, audioChannels);
|
|
310
|
-
}
|
|
558
|
+
});
|
|
311
559
|
};
|
|
312
560
|
|
|
313
561
|
/**
|
|
@@ -323,4 +571,112 @@ export const stopAllAudio = async (): Promise<void> => {
|
|
|
323
571
|
stopPromises.push(stopAllAudioInChannel(index));
|
|
324
572
|
});
|
|
325
573
|
await Promise.all(stopPromises);
|
|
326
|
-
};
|
|
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
|
+
};
|