title: Android Gapless Audio Looping
body: <p>This question has been asked several times, but so far I have tried every single solution including custom ones and the result is not ideal.</p>
  
  <p><strong>I'm trying to acheieve consistent gapless audio looping in an app and so far I've only achieved it inconsistently.</strong></p>
  
  <p>I have an app that loops audio files which are 14 seconds / 14200ms long. (I exported them all myself to .ogg and the lengths are all the same.</p>
  
  <p>mediaPlayer.setLooping(true); simply does not acheive gapless loops, regardless of file format. I've tried .mp3, .wav, and .ogg for every solution.</p>
  
  <p>The same goes for mediaPlayer1.setOnCompletionListener and alternating between 2 mediaplayers.</p>
  
  <p>My custom solution (which is currently my best), is this:</p>
  
  <p>I calculate how long the file is in milliseconds(14200) and start a runnable which is delayed to start in 14200 - 30 milliseconds. then, play3 runnable would start mediaplayer1 and keep looping.</p>
  
  <p>relevant code:</p>
  
  <pre><code>    durationHandler.postDelayed(play2, mediaPlayer1.getDuration() - 30);
      mediaPlayer1.start();
  
  }
  
  private Runnable play2 = new Runnable() {
      public void run() {
          durationHandler.postDelayed(play3, mediaPlayer2.getDuration() - 30);
              mediaPlayer2.start();
  
      }
  };
  </code></pre>
  
  <p>This code actually works really well SOMETIMES, but not every time. For example, the first loop might have a little gap but the second loop times out perfectly. My guess is that it has something to do with the actual phone taking a bit longer or shorter of time to process the code. Does that make sense?</p>
  
  <p>I tried soundpool and it won't work for 14 second files.</p>
  
  <p>If anyone has any other suggestions for CONSISTENT gapless looping of 14 second files I'd love to hear them.</p>