AudioRecord 与 AudioTrack

AudioRecord录制原始声音PCM数据
==========================================================================================
构造方法
AudioRecord(
            int audioSource,
            int sampleRateInHz, 
            int channelConfig, 
            int audioFormat, 
            int bufferSizeInBytes)
    audioSource
        录音源,查看 MediaRecorder.AudioSource类
        { MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.DEFAULT } 静态字段
        
    sampleRateInHz
        设置音频数据的采样率
        44100是目前的标准,但是某些设备仍然支持22050,16000,11025
        
    channelConfig
        设置音频的录制的声道
        AudioFormat.CHANNEL_IN_STEREO为双声道
        AudioFormat.CHANNEL_CONFIGURATION_MONO为单声道
        
    audioFormat
        音频数据格式
        PCM16位每个样本,保证设备支持。(AudioFormat.ENCODING_PCM_16BIT)
        PCM8位每个样本,不一定能得到设备支持。(AudioFormat.ENCODING_PCM_8BIT)

    bufferSizeInBytes
        缓存大小, 可根据静态方法getMinBufferSize获得
        AudioRecord.getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat)

常用方法
    startRecording()  开始录音
    stop() 停止录音
    release() 释放资源
    read(byte[] audioData, int offsetInBytes, int sizeInBytes) 读取录音数据 (8位)
    read(short[] audioData, int offsetInShorts, int sizeInShorts) 读取录音数据 (16位)
==========================================================================================
AudioTrack播放原始声音PCM数据
==========================================================================================
构造方法
AudioTrack(
            int streamType, 
            int sampleRateInHz, 
            int channelConfig, 
            int audioFormat, 
            int bufferSizeInBytes, 
            int mode)
    streamType
        指定在流的类型
        AudioManager.STREAM_ALARM:警告声
        AudioManager.STREAM_MUSCI:音乐声
        AudioManager.STREAM_RING:铃声
        AudioManager.STREAM_SYSTEM:系统声音
        AudioManager.STREAM_VOCIE_CALL:电话声音
        
    sampleRateInHz
        参见AudioRecord
        
    channelConfig    
        参见AudioRecord
        
    audioFormat
        参见AudioRecord
        
    bufferSizeInBytes
        参见AudioRecord
        
    mode    
        设置模式类型,在这里设置为流类型
        AudioTrack中有MODE_STATIC和MODE_STREAM两种分类。
        STREAM方式表示由用户通过write方式把数据一次一次得写到audiotrack中。
        这种方式的缺点就是JAVA层和Native层不断地交换数据,效率损失较大。
        而STATIC方式表示是一开始创建的时候,就把音频数据放到一个固定的buffer,然后直接传给audiotrack,
        后续就不用一次次得write了。AudioTrack会自己播放这个buffer中的数据。
        这种方法对于铃声等体积较小的文件比较合适。
    
常用方法
    play()
    pause()
    flush()
    stop()
    release()
    write(byte[] audioData, int offsetInBytes, int sizeInBytes) 写入声音数据8位
    write(short[] audioData, int offsetInShorts, int sizeInShorts) 写入声音数据16位
==========================================================================================

AudioRecord开始录音后,开启线程去读取录音的数据
AudioTrack开始播放后,开启线程去写入数据发声

原文地址:https://www.cnblogs.com/smile365/p/3336467.html