Spaces:
Paused
Paused
File size: 1,573 Bytes
55bd140 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
export class AudioQueue {
constructor(audioElement) {
this.audio = audioElement;
this.queue = [];
this.current = null;
this.id = null;
this._onEnded = () => this.next();
this.audio.addEventListener('ended', this._onEnded);
this.onStopped = null; // optional callback
}
setId(newId) {
console.log('Setting audio queue ID to:', newId);
if (this.id !== newId) {
this.stop();
this.id = newId;
if (this.onStopped) this.onStopped({ event: 'id-change', id: newId });
}
}
setPlaybackRate(rate) {
console.log('Setting audio playback rate to:', rate);
this.audio.playbackRate = rate;
}
enqueue(url) {
console.log('Enqueuing audio URL:', url);
this.queue.push(url);
// Auto-play if nothing is currently playing or loaded
if (this.audio.paused && !this.current) {
this.next();
}
}
play() {
if (!this.current && this.queue.length > 0) {
this.next();
} else {
this.audio.play();
}
}
next() {
this.current = this.queue.shift();
if (this.current) {
this.audio.src = this.current;
this.audio.play();
console.log('Playing audio URL:', this.current);
} else {
this.stop();
if (this.onStopped) this.onStopped({ event: 'empty-queue', id: this.id });
}
}
stop() {
this.audio.pause();
this.audio.currentTime = 0;
this.audio.src = '';
this.queue = [];
this.current = null;
if (this.onStopped) this.onStopped({ event: 'stop', id: this.id });
}
destroy() {
this.audio.removeEventListener('ended', this._onEnded);
this.stop();
this.onStopped = null;
this.audio = null;
}
}
|