音频的录制我们需要使用到 AudioRecord 这个大杀器,大致流程图如下。
音频录制比较简单,参考官方文档即可。这里需要开启两条线程,因为目前使用的编码是同步模式,如果是在一条线程里处理数据,会导致麦克风的数据丢失。
关键代码如下:
初始化AudioRecord
指定单声道模式,采样率为 44100,每个采样点 16 比特
int bufferSize = AudioRecord.getMinBufferSize(
configuration.getSampleRate(), C.AudioParams.CHANNEL,
C.AudioParams.BITS_PER_SAMPLE);
recorder = new AudioRecord(
MediaRecorder.AudioSource.MIC, configuration.getSampleRate(),
C.AudioParams.CHANNEL, C.AudioParams.BITS_PER_SAMPLE, bufferSize);
复制代码
初始化MediaCodec
MediaFormat audioFormat = MediaFormat.createAudioFormat(C.AudioParams.MIME_TYPE,
C.AudioParams.SAMPLE_RATE, C.AudioParams.CHANNEL_COUNT);
audioFormat.setInteger(MediaFormat.KEY_AAC_PROFILE,
MediaCodecInfo.CodecProfileLevel.AACObjectLC);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_MASK, C.AudioParams.CHANNEL);
audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, C.AudioParams.BIT_RATE);
audioFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, C.AudioParams.CHANNEL_COUNT);
audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 1024 * 4);
encoder = MediaCodec.createEncoderByType(C.AudioParams.MIME_TYPE);
encoder.configure(aud
ioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
bufferInfo = new MediaCodec.BufferInfo();
mStream = new BufferedOutputStream(new FileOutputStream(configuration.getFileName()));
复制代码
音频编码
读取音频数据
byte[] buffer = new byte[configuration.getSamplePerFrame()];
int bytes = recorder.read(buffer, 0, buffer.length);
if (bytes > 0) {
encode(buffer, bytes);
}
复制代码
塞进MediaCodec缓冲区
private void onEncode(byte[] data, int length) {