有一次我陷入了一个 javascript 项目。我想在事件发生时播放 mp3 音频文件。有时我需要立即连续播放 5 个 mp3 文件。在我的实验中,所有文件都会同时播放。我想要的是让他们按顺序比赛。循环收听 mp3 文件。当收到新的 mp3 播放请求时,我希望它将 100 个 mp3 文件添加到队列中并全部播放。我尝试使用 Howler.js 进行实验。
connection.on("send", (data) => {
playSound(data.mp3Filename) // --> I'm listen the mp3 files here.
});
var sound = null;
var soundQueue = [];
function playSound(soundURL) {
if (sound === null || !sound.playing()) {
sound = new Howl({
src: [soundURL],
onend: function () {
if (soundQueue.length > 0) {
var nextSound = soundQueue.shift();
playSound(nextSound);
}
},
});
sound.play();
} else {
soundQueue.push(soundURL);
}
}
但是 soundQueue 播放的数量仍然多于添加的数量,我的错误在哪里?
我解决了问题,上面的代码没有错误。它在我调用该函数的地方额外循环。谢谢大家。