Add a loop audio button

Ok, in case anybody is interested (@milad, @Ribeiro, @Jord, @Shiori), I found a way to do this with a script (thanks to ChatGPT!). Just add this code to the template where you want to have the button.

Simple version:

<div id="audio-container">
  <audio id="audio-player">
  <source src="{{Loop}}" type="audio/mpeg" />
</audio>
  <button id="loop-button">Loop Audio</button>
</div>

<script>
  document.getElementById('loop-button').addEventListener('click', function() {
    var audio = document.getElementById('audio-player');
    if (audio.loop) {
      audio.loop = false;
      this.innerText = 'Loop Audio';
    } else {
      audio.loop = true;
      this.innerText = 'Stop Loop';
      audio.play();
    }
  });
</script>

Version with images for starting/pausing the looping (you can use any image you want, just add it to your collection.media folder with an underscore at the beginning of the filename and change it here in the src="_FILENAME.EXT" sections, theres the _loop.svg to start it and the _pause.svg to stop it).

There is also a loop counter to know how many times you’ve listened to it.

<div id="audio-container">
  <audio id="audio-player">
  <source src="{{Loop}}" type="audio/mpeg" />
</audio>
  <button id="loop-button" class="loop-button">
    <img id="loop-image" src="_loop.svg" alt="Loop">
  </button>
  <div>Loop Count:<span id="loop-count" class="loop-count">0</span></div>
</div>

<script>
  var audio = document.getElementById('audio-player');
  var loopButton = document.getElementById('loop-button');
  var loopImage = document.getElementById('loop-image');
  var loopCount = document.getElementById('loop-count');
  var count = 0;
  var isLooping = false;

  loopButton.addEventListener('click', function() {
    isLooping = !isLooping;
    if (isLooping) {
      loopImage.src = '_pause.svg';
      loopImage.alt = 'Pause';
      audio.loop = false; // Disable native loop to handle it manually
      audio.play();
    } else {
      loopImage.src = '_loop.svg';
      loopImage.alt = 'Loop';
      audio.loop = false;
      audio.pause(); // Pause the audio immediately
      audio.currentTime = 0; // Reset the audio to the beginning
    }
    console.log('Loop button clicked, isLooping:', isLooping);
  });

  audio.addEventListener('ended', function() {
    console.log('Audio ended, isLooping:', isLooping);
    if (isLooping) {
      count++;
      loopCount.textContent = count;
      console.log('Loop count incremented:', count);
      audio.currentTime = 0;
      audio.play(); // Manually restart the audio
    }
  });
</script>

Note that the audio file should not have [sound:] tag, it should be just the filename (I used the Advanced Copy addon to duplicate my {{Audio}} field into a {{Loop}} field and then removed the tags with Find and Replace in the Browser).

Hope this is useful!

4 Likes