I am trying to make an audio file (jump.mp3)
loop using Howler.js. However, the audio only plays once and does not repeat after it ends.
What I expected:
What happens:
How can I modify my code to ensure the audio repeats automatically after it finishes playing?
Here is a full Stackblitz Demo.
Here is my code:
<!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,
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>
You just need to add loop: true
into the Howl settings.
this.sounds[audioFile] = new Howl({
src: [audioFile],
volume: this.volume,
preload: true,
onend: () => {},
loop: true,
});