AudioTrack lag: obtainBuffer timed out

女生的网名这么多〃 提交于 2019-12-03 02:48:01

I ran into a similar problem, although I was using a RandomAccessFile, instead of a BufferedInputStream, to read the PCM data. The issue was that the file I/O was too slow. I suspect you will have this problem even with a buffered stream, because the I/O is still taking place on the same thread as audio processing.

The solution is to have two threads: A thread that reads buffers from a file and queues them into memory, and another thread that reads from this queue and writes to the audio hardware. I used a ConcurrentLinkedQueue to accomplish this.

I used the same technique for recording, using AudioRecord, but in the reverse direction. The key is to place the file I/O on a separate thread.

A bit late to the party answering this, but in case it helps anyone in the future - I ran into this exact problem with code pretty similar to the code in the question, where the AudioTrack is created and set to play, but not written to immediately.

I found that creating the AudioTrack immediately before you start writing to it made the delay go away. For some reason AudioTrack doesn't seem to like sitting around with an empty buffer.

In terms of the code above, you'd want to do something like

mAudioTrack=null;
while (mRun) 
{ 

    // This flag is turned on when the user presses "play" 
    while (mPlaying) 
    { 

        try 
        { 
            if (mAudioTrack==null) {   
                mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, ConfigManager.SAMPLE_RATE,AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT,ConfigManager.AUDIO_BUFFER_LENGTH,AudioTrack.MODE_STREAM);   
                mAudioTrack.play();   
            }
            // Rest of the playback code here
        }
    }
    mAudioTrack=null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!