代码之家  ›  专栏  ›  技术社区  ›  coder

音频播放结束后,我该如何循环播放?

  •  1
  • coder  · 技术社区  · 6 月前

    我正在尝试重放音频文件 (jump.mp3) 使用Howler.js。但是,音频只播放一次,结束后不会重复。

    我所期待的:

    • 音频到达末尾后应循环播放(自动重复)。

    发生了什么:

    • 音频只播放一次,结束后不会重复。

    我如何修改我的代码以确保音频在播放结束后自动重复?

    这是一个完整的 Stackblitz Demo .

    这是我的代码:

    <!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/[email protected]/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>
    
    1 回复  |  直到 6 月前
        1
  •  3
  •   Eloi    6 月前

    你只需要添加 loop: true 进入嚎叫设置。

    this.sounds[audioFile] = new Howl({
                  src: [audioFile],
                  volume: this.volume,
                  preload: true,
                  onend: () => {},
                  loop: true,
                });
    
    推荐文章