javaandroidaudiosignal-processingaudiotrack

AudioTrack WRITE_BLOCKING vs WRITE_NON_BLOCKING


I am trying to figure out exactly how Android AudioTrack works. One point of confusion for me is the write mode.

The documentation for the write() method indicates that you can pass either a write mode WRITE_BLOCKING or WRITE_NON_BLOCKING.

Based on the descriptions, does WRITE_BLOCKING block until all data has been played? So for example, if I have a buffer of mono audio at 44100 of size 2048 samples, calling write with WRITE_BLOCKING will block for 2048 * (1000.0 / 44100) milliseconds? Does this not mean that as soon as the write is complete, that you are immediately in a buffer underrun scenario?


Solution

  • As @Michael mentioned, it blocks until the data has been enqueued. This is the same meaning as in the description for WRITE_BLOCKING; it blocks until the data has been written to the internal buffer (the one for which you specified the size, during construction).

    write( ..., 2048, WRITE_BLOCKING ) will block for approximately 2048 * (1000.0 / 44100) seconds, if the buffer is already full (data hasn't been played yet). If write() does block for any length of time, once it returns, you can be reasonably sure the internal buffer is maximally filled. In the absence of any further write()s, the AudioTrack will continue to supply the mixer with audio output, until the internal buffer is exhausted.

    This design (internal buffer) is supposed to help you avoid buffer underruns. The bigger your buffer is, the longer you can go without a write().