Android MediaCodec 录制音频功能实现的完整代码
时间: 2023-10-13 19:04:13 浏览: 145
以下是使用Android MediaCodec录制音频的完整代码:
```java
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
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 static final int TIMEOUT_US = 10000;
private MediaCodec mediaCodec;
private MediaMuxer mediaMuxer;
private int audioTrackIndex;
private boolean isRecording;
public void startRecording() {
try {
mediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
MediaFormat mediaFormat = MediaFormat.createAudioFormat(MIME_TYPE, SAMPLE_RATE, CHANNEL_COUNT);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
mediaFormat.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();
File outputFile = new File(Environment.getExternalStorageDirectory(), "audio.mp4");
mediaMuxer = new MediaMuxer(outputFile.getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
audioTrackIndex = mediaMuxer.addTrack(mediaCodec.getOutputFormat());
mediaMuxer.start();
isRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopRecording() {
isRecording = false;
mediaCodec.stop();
mediaCodec.release();
mediaMuxer.stop();
mediaMuxer.release();
}
public void putAudioData(byte[] data) {
if (!isRecording) {
return;
}
int inputBufferIndex = mediaCodec.dequeueInputBuffer(TIMEOUT_US);
if (inputBufferIndex >= 0) {
ByteBuffer inputBuffer = mediaCodec.getInputBuffer(inputBufferIndex);
inputBuffer.clear();
inputBuffer.put(data);
mediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, System.nanoTime() / 1000, 0);
}
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputBufferIndex;
while ((outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, TIMEOUT_US)) >= 0) {
ByteBuffer outputBuffer = mediaCodec.getOutputBuffer(outputBufferIndex);
outputBuffer.position(bufferInfo.offset);
outputBuffer.limit(bufferInfo.offset + bufferInfo.size);
mediaMuxer.writeSampleData(audioTrackIndex, outputBuffer, bufferInfo);
mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
}
}
}
```
该代码使用MediaCodec录制音频,并将录制的数据写入MP4文件中。在startRecording()方法中,我们首先创建一个MediaCodec实例并配置它的初始化参数。然后,我们创建一个MediaMuxer实例,将MediaCodec的输出格式添加到MediaMuxer中,并开始写入数据到输出文件。
在putAudioData()方法中,我们将音频数据放入MediaCodec的输入缓冲区,并在之后从MediaCodec的输出缓冲区中读取数据,并将其写入MediaMuxer中。
最后,在stopRecording()方法中,我们停止录制并释放MediaCodec和MediaMuxer。
阅读全文