title: Create Seamless Loop of Audio - Web
body: <p>I want to create a seamless loop of an audio file. But in all approaches I used so far, there was a noticeable gap between end &amp; start.</p>
  
  <hr>
  
  <p><strong>This is what I tried so far:</strong></p>
  
  <p>First approach was to use the audio in the HTML and it loops but there is still a noticeable delay when going from the end of the track to the beginning.</p>
  
  <pre><code>&lt;audio loop autoplay&gt;
      &lt;source src="audio.mp3" type="audio/mpeg"&gt;
  &lt;audio&gt;
  </code></pre>
  
  <p>Then I tried it from JavaScript with the same result:</p>
  
  <pre><code>let myAudio = new Audio(file);
  myAudio.loop = true; 
  myAudio.play();
  </code></pre>
  
  <p>After that I tried this (according to <a href="https://stackoverflow.com/a/22446616/5504438">this answer</a>) </p>
  
  <pre><code>myAudio.addEventListener(
      'timeupdate',
      function() {
          var buffer = .44;
          if (this.currentTime &gt; this.duration - buffer) {
              this.currentTime = 0;
              this.play();
          }
       },
       false
  );
  </code></pre>
  
  <p>I played around with the buffer but I only got it to reduce the gap but not leave it out entirely.</p>
  
  <p>I turned to the library <code>SeamlessLoop</code> (<a href="https://github.com/Hivenfour/SeamlessLoop" rel="noreferrer">GitHub</a>) and got it to work to loop seamlessly in Chromium browsers (but not in the latest Safari. Didn't test in other browsers). Code I used for that:</p>
  
  <pre><code>let loop = new SeamlessLoop();
  // My File is 58 Seconds long. Btw there aren't any gaps in the file.
  loop.addUri(file, 58000, 'sound1');
  loop.callback(soundsLoaded);
  function soundsLoaded() {
      let n = 1;
      loop.start('sound' + n);
  }
  </code></pre>
  
  <p><strong>EDIT:</strong> I tried another approach: Looping it trough two different audio elements:</p>
  
  <pre><code>var current_player = "a";
  var player_a = document.createElement("audio");
  var player_b = document.createElement("audio");
  
  player_a.src = "sounds/back_music.ogg";
  player_b.src = player_a.src;
  
  function loopIt(){
      var player = null;
  
      if(current_player == "a"){
          player = player_b;
          current_player = "b";
      }
      else{
          player = player_a;
          current_player = "a";
      }
  
      player.play();
  
      /*
          3104.897 is the length of the audio clip in milliseconds.
          Received from player.duration. 
          This is a different file than the first one
      */
      setTimeout(loopIt, 3104.897); 
  }
  
  loopIt();
  </code></pre>
  
  <p>But as milliseconds in browsers are not consistent or granular enough this doesn't work too well but it does work much better than the normal "loop" property of the audio.</p>
  
  <hr>
  
  <p>Can anyone guide me into the right direction to loop the audio seamlessly?</p>