Android:录制和收听音频

时间:2014-07-14 21:12:29

标签: android audio media-player audio-streaming audio-recording

我尝试实现记录并从不同的帖子中听取音频,但我有40毫秒的延迟。

这是我的代码。

public class record {
    private AudioRecord recorder = null;
    private boolean isRecording = false;
    private int SAMPLERATE = 8000;
    private int CHANNELS = AudioFormat.CHANNEL_CONFIGURATION_MONO;
    private int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    private int bufferSize = AudioRecord.getMinBufferSize(SAMPLERATE, CHANNELS,
                    AUDIO_FORMAT);
    private Thread recordingThread = null;

    public void startRecording() {
            recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLERATE,
                            CHANNELS, AUDIO_FORMAT, bufferSize);

            recorder.startRecording();
            isRecording = true;

            recordingThread = new Thread(new Runnable()

            {
                    public void run() {
                            writeAudioData();
                    }

            });
            recordingThread.start();

    }

    public void stopRecording() {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
    }

    private void writeAudioData() {

            byte data[] = new byte[bufferSize];

            int buff = 8000;
            int minBufferSize = AudioTrack.getMinBufferSize(buff,
                            AudioFormat.CHANNEL_CONFIGURATION_MONO,
                            AudioFormat.ENCODING_PCM_16BIT);

            Log.i("AUDIO", "BufferSize:" + minBufferSize);

            AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, buff,
                            AudioFormat.CHANNEL_CONFIGURATION_MONO,
                            AudioFormat.ENCODING_PCM_16BIT, minBufferSize,
                            AudioTrack.MODE_STREAM);

            at.play();

            while (isRecording) {
                    recorder.read(data, 0, bufferSize);
                    at.write(data, 0, bufferSize);
            }
            at.stop();
            at.release();
    }

}

如何减少延迟?我尝试减少缓冲区,但问题仍然存在。

1 个答案:

答案 0 :(得分:-1)

根据测量对象和方法的不同,Android音频系统可能有数十毫秒的延迟或数百毫秒的延迟。

如果测量播放和录制之间的延迟,40ms延迟是正常值,实际上我在Android 4.4.3的测试中看到了30~50ms的延迟值:

  

https://github.com/garyyu/AudioTracker-Test

此外,如果您检查打印的“minBufferSize”值,您会发现此最小缓冲区大小为40毫秒(在我的Nexus7 2013上)。当你玩游戏时有帧延迟,我们不能指望在调用“at.write()”时立即播放,我猜在内部还有另一个缓冲区来存储你的“写入”数据。在录音方面也一样。因此,如果从播放开始功能调用到真实声音输出进行测量,则会有比40ms更多的延迟 如果需要更多建议,您需要描述有关如何衡量延迟的详细信息。