Howler.js 是一个现代的 Web 音频库,支持 Web Audio API 和 HTML5 Audio 回退。jQuery 是一个流行的 JavaScript 库,简化了 DOM 操作和事件处理。
当使用 Howler.js 和 jQuery 时,要在播放新声音时停止所有当前播放的声音,你可以采用以下方法:
// 创建一个全局的 Howler 声音管理器
var soundManager = {
sounds: [],
// 播放新声音并停止所有其他声音
playNewSound: function(src) {
// 停止所有当前播放的声音
this.stopAllSounds();
// 创建并播放新声音
var sound = new Howl({
src: [src],
autoplay: true,
onend: function() {
// 从管理器中移除已结束的声音
soundManager.removeSound(this);
}
});
// 将新声音添加到管理器
this.sounds.push(sound);
},
// 停止所有声音
stopAllSounds: function() {
this.sounds.forEach(function(sound) {
sound.stop();
});
this.sounds = []; // 清空数组
},
// 从管理器中移除特定声音
removeSound: function(sound) {
this.sounds = this.sounds.filter(function(s) {
return s !== sound;
});
}
};
// 使用jQuery绑定点击事件
$(document).ready(function() {
$('.play-button').click(function() {
var soundFile = $(this).data('sound');
soundManager.playNewSound(soundFile);
});
});
// 存储当前播放的声音
var currentSound = null;
$(document).ready(function() {
$('.play-button').click(function() {
var soundFile = $(this).data('sound');
// 停止当前播放的声音
if (currentSound) {
currentSound.stop();
}
// 创建并播放新声音
currentSound = new Howl({
src: [soundFile],
autoplay: true
});
});
});
这种技术适用于: