android MediaMuxer使用示例
时间: 2023-07-11 11:37:20 浏览: 67
好的,这里是一个简单的Android MediaMuxer使用示例:
```java
public class MediaMuxerActivity extends Activity {
private static final String TAG = "MediaMuxerActivity";
private static final String VIDEO_MIME_TYPE = "video/avc";
private static final int VIDEO_FRAME_RATE = 30;
private static final int VIDEO_I_FRAME_INTERVAL = 5;
private static final int VIDEO_WIDTH = 720;
private static final int VIDEO_HEIGHT = 1280;
private MediaMuxer mMediaMuxer;
private int mVideoTrackIndex;
private long mLastVideoPresentationTimeUs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_muxer);
setUpMediaMuxer();
}
private void setUpMediaMuxer() {
try {
// Create a MediaMuxer. This will create a new file with the specified name.
mMediaMuxer = new MediaMuxer(getFilesDir() + "/output.mp4", MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
// Add the video track to the MediaMuxer.
MediaFormat videoFormat = MediaFormat.createVideoFormat(VIDEO_MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT);
videoFormat.setInteger(MediaFormat.KEY_BIT_RATE, 2000000);
videoFormat.setInteger(MediaFormat.KEY_FRAME_RATE, VIDEO_FRAME_RATE);
videoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, VIDEO_I_FRAME_INTERVAL);
mVideoTrackIndex = mMediaMuxer.addTrack(videoFormat);
// Start the MediaMuxer.
mMediaMuxer.start();
} catch (IOException e) {
Log.e(TAG, "setUpMediaMuxer failed", e);
}
}
public void writeVideoFrame(byte[] data) {
if (mMediaMuxer == null || mVideoTrackIndex < 0) {
return;
}
// Create a ByteBuffer from the video data.
ByteBuffer videoBuffer = ByteBuffer.wrap(data);
// Calculate the presentation time of the video frame.
long videoPresentationTimeUs = (System.nanoTime() - mLastVideoPresentationTimeUs) / 1000;
mLastVideoPresentationTimeUs = System.nanoTime();
// Write the video data to the MediaMuxer.
MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
videoBufferInfo.offset = 0;
videoBufferInfo.size = data.length;
videoBufferInfo.presentationTimeUs = videoPresentationTimeUs;
videoBufferInfo.flags = MediaCodec.BUFFER_FLAG_KEY_FRAME;
mMediaMuxer.writeSampleData(mVideoTrackIndex, videoBuffer, videoBufferInfo);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Stop and release the MediaMuxer.
if (mMediaMuxer != null) {
mMediaMuxer.stop();
mMediaMuxer.release();
mMediaMuxer = null;
}
}
}
```
这个示例演示了如何使用MediaMuxer在Android中编写视频文件。在 `setUpMediaMuxer()` 方法中,我们创建了一个新的 `MediaMuxer` 对象,并为视频轨道添加了一个 `MediaFormat` 对象。然后,在 `writeVideoFrame()` 方法中,我们将视频数据写入 `MediaMuxer`。最后,在 `onDestroy()` 方法中,我们停止并释放了 `MediaMuxer`。