AudioRecord回调给多个MediaCodec编码的示例代码
时间: 2023-12-10 19:05:48 浏览: 99
mediacodec实例代码
以下是一个AudioRecord回调给多个MediaCodec编码的示例代码:
```java
public class AudioEncoder {
private static final String TAG = "AudioEncoder";
private static final String MIME_TYPE = "audio/mp4a-latm";
private static final int SAMPLE_RATE = 44100;
private static final int CHANNEL_COUNT = 1;
private static final int BIT_RATE = 64000;
private AudioRecord mAudioRecord;
private MediaCodec mMediaCodec;
private boolean mIsRecording;
private ByteBuffer[] mInputBuffers;
private ByteBuffer[] mOutputBuffers;
private MediaCodec.BufferInfo mBufferInfo;
private List<MediaMuxerWrapper> mMuxerWrappers;
public void startRecording() {
mIsRecording = true;
mAudioRecord.startRecording();
try {
mMediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
MediaFormat format = MediaFormat.createAudioFormat(MIME_TYPE, SAMPLE_RATE, CHANNEL_COUNT);
format.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectLC);
mMediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
mInputBuffers = mMediaCodec.getInputBuffers();
mOutputBuffers = mMediaCodec.getOutputBuffers();
mBufferInfo = new MediaCodec.BufferInfo();
new Thread(new Runnable() {
@Override
public void run() {
while (mIsRecording) {
int index = mMediaCodec.dequeueInputBuffer(-1);
if (index >= 0) {
ByteBuffer inputBuffer = mInputBuffers[index];
inputBuffer.clear();
int bufferSize = mAudioRecord.read(inputBuffer, inputBuffer.capacity());
if (bufferSize >= 0) {
long presentationTimeUs = System.nanoTime() / 1000;
mMediaCodec.queueInputBuffer(index, 0, bufferSize, presentationTimeUs, 0);
}
}
int outputIndex = mMediaCodec.dequeueOutputBuffer(mBufferInfo, 0);
while (outputIndex >= 0) {
ByteBuffer outputBuffer = mOutputBuffers[outputIndex];
outputBuffer.position(mBufferInfo.offset);
outputBuffer.limit(mBufferInfo.offset + mBufferInfo.size);
for (MediaMuxerWrapper muxerWrapper : mMuxerWrappers) {
muxerWrapper.writeSampleData(AudioMuxerWrapper.TRACK_INDEX, outputBuffer, mBufferInfo);
}
mMediaCodec.releaseOutputBuffer(outputIndex, false);
outputIndex = mMediaCodec.dequeueOutputBuffer(mBufferInfo, 0);
}
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopRecording() {
mIsRecording = false;
mAudioRecord.stop();
mMediaCodec.stop();
mMediaCodec.release();
}
public void addMuxerWrapper(MediaMuxerWrapper muxerWrapper) {
mMuxerWrappers.add(muxerWrapper);
}
}
```
这个示例代码中,我们启动一个AudioRecord对象,然后启动一个MediaCodec对象,使用MediaCodec API将音频数据编码为AAC格式。我们将编码器的输出提供给一个MediaMuxerWrapper对象,它可以将音频数据写入一个MP4文件中。我们可以在不同的线程中同时启动多个MediaMuxerWrapper对象,这样我们就可以将音频数据写入多个MP4文件中。
阅读全文