在Android Audio Track中写入缓冲区后,音频文件播放较晚

时间:2014-07-17 06:21:24

标签: java android audio buffer audiotrack

当我增加缓冲区的大小时,将在缓冲区上写入的音频声音播放得晚。当我将缓冲区的大小分开时,文件正确播放意味着文件播放时间不晚。任何人都可以帮忙...缓冲区大小是64k。

public class MediaSPK
{
    private static final int RECORDER_SAMPLERATE = 16000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_OUT_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

    VaxSIPUserAgent m_objVaxSIPUserAgent;

    boolean m_bMuteSpk = false;
    boolean m_bPlay = false;

    AudioTrack m_objAudioTrack = null;

    public MediaSPK(VaxSIPUserAgent objVaxSIPUserAgent)
    {
        m_objVaxSIPUserAgent = objVaxSIPUserAgent;
    }

    public void OpenSpk() 
    {
        int nMinBuffSize = AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);

        //Log.i("size SPK", "" + m_nMinBuffSize);

        m_objAudioTrack = new  AudioTrack(AudioManager.STREAM_VOICE_CALL, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, 64000, AudioTrack.MODE_STREAM);
        m_objAudioTrack.play();

        m_bPlay = false;
    }

    public void PlaySpk(byte[] aData, int nDataSize)
    {
        if(m_bMuteSpk)
        {
            byte[] aDataSilence = new byte[nDataSize];
            m_objAudioTrack.write(aDataSilence, 0, nDataSize);
        }
        else
        {
            m_objAudioTrack.write(aData, 0, nDataSize);
        }
    }

    public void Mute(boolean bEnable)
    {
        //m_bMuteSpk = bEnable;

        //m_objAudioTrack
    }

    public void CloseSpk() 
    {
        if(m_objAudioTrack == null)
            return;

        try 
        {
            m_objAudioTrack.stop();
            m_objAudioTrack.release();
            m_objAudioTrack = null;
        } 
        catch (IllegalStateException e) 
        {
            e.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:0)

可能是你把整个操作放在单个线程上尝试拆分操作使用

在一个单独的线程中播放音频
Handler mHandler = new Handler();

mHandler.postDelayed(new Runnable(), delay);