如何使用Howler.js实现音频文件自动循环播放?
Howler.js音频无法自动循环播放的解决方法
我尝试使用Howler.js实现音频文件jump.mp3的循环播放,但音频仅播放一次,结束后不会重复。
预期效果
- 音频播放至结尾后应自动循环(重复)
实际情况
- 音频仅播放一次,结束后不会重复
解决方法
Howler.js内置了循环播放的配置项,直接在创建Howl实例时添加loop: true参数,就能实现音频自动循环。如果需要在音频结束时执行额外逻辑,也可以通过onend事件手动调用播放方法,但优先推荐官方内置的loop参数,更简洁高效。
修改后的核心代码片段
在AudioManager.load方法的Howl配置中新增循环设置:
this.sounds[audioFile] = new Howl({ src: [audioFile], volume: this.volume, preload: true, loop: true, // 启用自动循环 onend: () => {}, });
完整修改后的代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Audio Example</title> <link rel="stylesheet" href="style.css" /> </head> <body> <button onclick="repeatAudio()">Repeat Audio</button> <script src="https://cdn.jsdelivr.net/npm/howler@2.2.3/dist/howler.min.js"></script> <script> class AudioManager { static sounds = {}; static volume = 1; static load(audioFile) { if (!this.sounds[audioFile]) { this.sounds[audioFile] = new Howl({ src: [audioFile], volume: this.volume, preload: true, loop: true, // 启用自动循环 onend: () => {}, }); } } static play(audioFile) { if (!this.sounds[audioFile]) { this.load(audioFile); } this.sounds[audioFile].play(); } static replay(audioFile) { if (!this.sounds[audioFile]) { this.load(audioFile); } const sound = this.sounds[audioFile]; sound.stop(); sound.play(); } } function repeatAudio() { AudioManager.replay('jump.mp3'); } </script> </body> </html>
补充说明
如果后续需要动态切换循环状态,可以通过sound.loop(true)开启循环、sound.loop(false)关闭循环,调用sound.loop()可获取当前循环状态。
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

