Sunday, January 2, 2011

[android-developers] AudioTrack.write blocks in multi-threaded app

I would really appreciate some advice on using AudioTrack. I need to
be able to play a number of audio signals on demand, potentially mixed
together.

I have no problem setting AudioTrack up and writing an audio buffer to
it (originally captured by another Android device's AudioRecord and
received via network). However, when I try to put AudioTrack in its
own Runnable class, I run into problems. My current implementation
instantiates the AudioTrack in the constructor and, to keep things
simple, the run() function is a while loop that checks a Buffer queue
(modified version of http://www.siafoo.net/snippet/216 to use short
instead of byte) and writes anything over 100 bytes to AudioTrack. The
buffer queue fills fine, but as soon as I try to write it, the
AudioTrack blocks.

I am really not sure what relevant code to post, but here is a version
of my AudioTrack Runnable code with the irrelevant code missing:

public class SoundIn implements Runnable{

BufferQueue m_queue = null;

// Audio track to output audio on phone
AudioTrack m_audioTrack = null;

// Buffer size required to support AudioTrack
int m_BufferSize;

short[] m_outbuf;

public SoundIn(BufferQueue queue)
{
m_queue = queue;

// Get minimum supported buffer size
m_BufferSize = AudioTrack.getMinBufferSize(11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);

// Initialize a streaming audio track with minimum-size buffer
m_audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, m_BufferSize,
AudioTrack.MODE_STREAM);

m_audioTrack.play();

}

public void run()
{
int minsize;
m_outbuf = new short[50000];
while(true)
{
minsize = //...Get available data size

if (minsize == 0)
{
Log.d("SoundIn", "Sleeping...");
try{Thread.sleep(100);}
catch (Exception e){e.printStackTrace();}
continue;
}

//read available bytes from queue
m_queue().read(m_outbuf, 0, minsize);

//Gets here with m_outbuf correctly holding data
m_audioTrack.write(m_outbuf,0,minsize);
//Never gets here
}
}

}

Any suggestions on why the AudioTrack.write call might block in a
situation like this would be greatly appreciated.

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate