title: Audio Buffering in Android
body: <p>I'm trying to implement efficient audio buffer for radio streaming. Initally I was trying to do buffering as follows <img src="https://i.stack.imgur.com/1j6Lh.png" alt="Program Flow"></p>
  
  <p>So initially I have my <code>InputStream</code> which is taken from <code>HttpUrlConnection</code>. The data is being read from input stream by circular buffer which fills up the buffers. In this case I have 3 buffers but the amount and size of buffers can be easily changed. So after all buffers are filled up I start to write data from my first buffer to the <code>OutputStream</code> which is connected to <code>InputStream</code>, so whenever I write something to the <code>OutputStream</code> it can be then read from <code>InputStream</code>. <code>MediaCodec</code> is responsible for reading the data from <code>InputStream</code> and decoding the data which is then being passed to <code>AudioTrack</code>.</p>
  
  <p>The problem with this set up is that after a while OutputStream eventually reaches the end of circular buffer, so there is no more "extra buffer" in between <code>"OutputStream.giveMeNextBufferWithData"</code> and <code>"CircularBuffer.readDataFromInputStreamAndCreateBuffer"</code> (pseudo code).</p>
  
  <p>I've tried increasing the amount and size of each buffer, but that didn't help. It just delays the amount of time before <code>OutputStream</code> gets "hungry" for more data.</p>
  
  <p>There is one very good library <a href="https://code.google.com/p/aacdecoder-android/" rel="nofollow noreferrer">https://code.google.com/p/aacdecoder-android/</a> which works very well when it comes to buffer audio, but unfortunately I couldn't figure out how the buffering is done there and it doesn't work that well under some circumstances.</p>
  
  <p>So is there any "perfect" algorithm for such a task ? I was thinking about double/triple buffering but I'm not too sure about it and considering that I've been searching around the net and implementing different solutions with no success for last few days I eventually decided to ask her.</p>
  
  <p>I hope I explained everything well.</p>
  
  <p>Thank you all in advance !</p>