开发者

Streaming audio from a socket on Android using AudioTrack

I'm trying to play a PCM stream using the AudioTrack class. This is the code:

AudioTrack aud开发者_运维技巧ioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 20000, AudioTrack.MODE_STREAM);
audioTrack.play();
// Reading data.
byte[] data = new byte[200];
int n = 0;
try {
   while ((n = s.getInputStream().read(data)) != -1)
      audioTrack.write(data, 0, n);
}
catch (IOException e) {
   return;
}

Unfortunately, the audio I get is continuously interrupted. I tried to write down data in a file instead of writing to the audioTrack, and playing it with aplay. It seems it is perfect. No interruption. Is there anything wrong in the code I reported when using audioTrack? Or maybe simply the data is not arriving in time? Thanks!


Try putting the code in a separate thread with high priority.

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO)

In the run() of the thread read and write the data.


You could do a few checks:

  1. Use your code to read a file. Just open file as a stream.

  2. Measure throughput. Every time a chunk of data arrives, record time (System. nanoTime()) and length. Then you could calculate if data is arriving late.


Reading the audio data from a variable latency stream and sending it to audioTrack.write in the same thread will work poorly as you've observed. This is a job for 2 threads where one reads the data from the stream (and buffers a reasonable amount) while the other writes the audio data to the audioTrack object. You could potentially get away with reading and writing large blocks of audio data at a time, but the audioTrack class imposes limitations on that. When the audioTrack thread wakes up after a write operation, you cannot do significant work in that thread or you will cause gaps in the audio output; you must provide it with a continuous stream of data.


I've not used AudioTrack before, but comparing your version with this implementation the main difference I see is that you are creating your AudioTrack with a different buffersize than you are using for your own buffer: 20000 vs 200. I'd try using the same size for both.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜