Android MediaCodec 录制音频功能实现完整代码
时间: 2023-10-13 20:04:14 浏览: 125
Android实现录音完整代码
5星 · 资源好评率100%
以下是一个简单的 Android MediaCodec 录制音频的实现代码:
```
public class AudioRecorder {
private static final String MIME_TYPE = "audio/mp4a-latm"; //音频编码格式
private static final int SAMPLE_RATE = 44100; //采样率
private static final int BIT_RATE = 64000; //比特率
private static final int CHANNEL_COUNT = 1; //声道数量
private MediaCodec mMediaCodec;
private ByteBuffer[] mInputBuffers;
private ByteBuffer[] mOutputBuffers;
private MediaFormat mMediaFormat;
private boolean mIsRecording;
public void startRecording(String filePath) {
try {
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mMediaFormat = MediaFormat.createAudioFormat(MIME_TYPE, SAMPLE_RATE, CHANNEL_COUNT);
mMediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
mMediaCodec.configure(mMediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
mInputBuffers = mMediaCodec.getInputBuffers();
mOutputBuffers = mMediaCodec.getOutputBuffers();
FileOutputStream fos = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
mIsRecording = true;
while (mIsRecording) {
int inputBufferIndex = mMediaCodec.dequeueInputBuffer(-1);
if (inputBufferIndex >= 0) {
ByteBuffer inputBuffer = mInputBuffers[inputBufferIndex];
inputBuffer.clear();
short[] buffer = null; //这里应该是通过 AudioRecord 获取到 PCM 数据
//将 PCM 数据写入 inputBuffer
for (int i = 0; i < buffer.length; i++) {
inputBuffer.putShort(buffer[i]);
}
mMediaCodec.queueInputBuffer(inputBufferIndex, 0, buffer.length * 2, 0, 0);
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0);
while (outputBufferIndex >= 0) {
ByteBuffer outputBuffer = mOutputBuffers[outputBufferIndex];
byte[] outData = new byte[bufferInfo.size];
outputBuffer.get(outData);
bos.write(outData, 0, outData.length);
bos.flush();
mMediaCodec.releaseOutputBuffer(outputBufferIndex, false);
outputBufferIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 0);
}
}
}
mMediaCodec.stop();
mMediaCodec.release();
mMediaCodec = null;
bos.flush();
bos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopRecording() {
mIsRecording = false;
}
}
```
注意,该代码中的 `short[] buffer` 应该是通过 `AudioRecord` 获取到的 PCM 数据,本例未给出。同时,在实际应用中,应该在子线程中执行录音操作,以免阻塞主线程。
阅读全文