1. AAC音频编码流程
2. AAC音频编码代码
/**
* AAC音频编码
* AudioRecord + MediaCodec AAC编码
*/
public class MediaAudioEncoder implements Runnable {
// 麦克风
private AudioRecord audioRecord;
// 开启状态
private AtomicBoolean isStar = new AtomicBoolean(false);
// 数据架设监听
private OnAudioRecordListener onAudioRecordListener;
// 双声道,立体声
private int sampleRate = 44100;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
private int channels = 2;
// 编解码
private MediaCodec mediaCodec;
private int timeOutUs = 30;
public MediaAudioEncoder() {
// 找到系统的麦克风
audioRecord = chooseAudioRecord();
if (audioRecord == null) {
throw new RuntimeException("audioRecord is null");
}
Log.e("TAG", "AudioRecord channels " + channels);
initMediaCodec();
}
private void initMediaCodec() {
try {
MediaFormat format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_AAC, sampleRate, channels);
format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_AAC);
format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
format.setInteger(MediaFormat.KEY_BIT_RATE, getPcmBufferSize());
format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, getPcmBufferSize() * channels * 2);
mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_AAC);
mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
} catch (IOException e) {
e.printStackTrace();
}
}
public AudioRecord chooseAudioRecord() {
// AudioFormat.CHANNEL_IN_MONO;// 单声道
// AudioFormat.CHANNEL_IN_STEREO; // 双声道
int audioSource = MediaRecorder.AudioSource.DEFAULT;
// 1. 优先找立体声的
AudioRecord mic = new AudioRecord(audioSource, sampleRate,
AudioFormat.CHANNEL_IN_STEREO,
audioFormat, getPcmBufferSize() * 2);
// 2. 双通道不行,找单通道
if (mic.getState() != AudioRecord.STATE_INITIALIZED) {
mic = new AudioRecord(audioSource, sampleRate, AudioFormat.CHANNEL_IN_MONO,
audioFormat, getPcmBufferSize() * 2);
if (mic.getState() != AudioRecord.STATE_INITIALIZED) {
mic = null;
} else {
channels = 1;
}
} else {
channels = 2;
}
return mic;
}
private int getPcmBufferSize() {
// AudioFormat.CHANNEL_IN_MONO;// 单声道
// AudioFormat.CHANNEL_IN_STEREO; // 双声道
int pcmBufSize = AudioRecord.getMinBufferSize(44100,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT) + 8191;
return pcmBufSize - (pcmBufSize % 8192);
}
// 开始录音和AAC编码
public void start() {
if (isStar.compareAndSet(false, true)) {
// 拿到编码后AAC的数据
Executors.newSingleThreadExecutor().execute(readAacTask);
// 用麦克风录音 + MediaCodec编码音频数据
Executors.newSingleThreadExecutor().execute(this);
}
}
// 停止AAC录音和编码
public void stop() {
isStar.set(false);
}
// 读取编码后AAC的数据
private Runnable readAacTask = new Runnable() {
@Override
public void run() {
if (mediaCodec == null) {
return;
}
Log.e("TAG", "start read aac ....");
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
long pts = 0;
while (isStar.get()) {
try {
// 读取编码结果
int outIndex = mediaCodec.dequeueOutputBuffer(info, timeOutUs);
while (isStar.get() && outIndex >= 0) {
ByteBuffer buffer = mediaCodec.getOutputBuffer(outIndex);
buffer.position(info.offset);
buffer.limit(info.size);
byte[] data = new byte[info.size];
buffer.get(data);
if (pts == 0) {
pts = info.presentationTimeUs;
}
info.presentationTimeUs -= pts;
// 就是少了这句话
mediaCodec.releaseOutputBuffer(outIndex, false);
// AAC编码回调
if (onAudioRecordListener != null) {
onAudioRecordListener.onAudioRecord(data, info.size, channels, info.presentationTimeUs);
}
outIndex = mediaCodec.dequeueOutputBuffer(info, timeOutUs);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Log.e("TAG", "stop read aac....");
}
};
@Override
public void run() {
if (audioRecord == null || mediaCodec == null) {
return;
}
Log.e("TAG", "start aac encode ...");
mediaCodec.start();
// 开始录音(调用Android的API录制手机麦克风的声音)
audioRecord.startRecording();
int length = getPcmBufferSize();
ByteBuffer buffer = ByteBuffer.allocateDirect(length);
int readSize;
while (isStar.get()) {
try {
// 每次读多少数据要根据编码器来定!
readSize = audioRecord.read(buffer, length);
if (readSize > 0) {
// 这里是设置数据读到的位置
buffer.position(readSize);
buffer.flip();
// AAC编码
int index = mediaCodec.dequeueInputBuffer(timeOutUs);
if (index >= 0) {
ByteBuffer inputBuffer = mediaCodec.getInputBuffer(index);
// 将容量重置
inputBuffer.clear();
inputBuffer.put(buffer);
// 给MediaCodec塞数据
mediaCodec.queueInputBuffer(index, 0, readSize,
System.nanoTime() / 1000, 0);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 清空信息
release();
Log.e("TAG", "stop aac encode ....");
}
// 回收信息
private void release() {
onAudioRecordListener = null;
if (audioRecord != null) {
audioRecord.stop();
audioRecord.release();
audioRecord = null;
}
if (mediaCodec != null) {
mediaCodec.stop();
mediaCodec.release();
mediaCodec = null;
}
}
public interface OnAudioRecordListener {
void onAudioRecord(byte[] data, int len, int channels, long time);
}
public void setOnAudioRecordListener(OnAudioRecordListener onAudioRecordListener) {
this.onAudioRecordListener = onAudioRecordListener;
}
}