android app中用java实现将H264视频流保存到本地
时间: 2023-11-23 19:06:21 浏览: 86
Android保存App异常信息到本地
以下是用Java在Android应用程序中将H264视频流保存到本地的示例代码:
首先,你需要创建一个类来处理视频编码和保存:
```
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Environment;
import java.io.IOException;
import java.nio.ByteBuffer;
public class VideoEncoder {
private static final String MIME_TYPE = "video/avc"; // H.264 Advanced Video Coding
private static final int FRAME_RATE = 30; // 帧率
private static final int I_FRAME_INTERVAL = 1; // I帧间隔(单位秒)
private static final int BIT_RATE = 125000; // 比特率(单位bps)
private MediaCodec mediaCodec;
private MediaMuxer mediaMuxer;
private int trackIndex;
private boolean isMuxerStarted;
public VideoEncoder() throws IOException {
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, 640, 480);
format.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE);
format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, I_FRAME_INTERVAL);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
mediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();
mediaMuxer = new MediaMuxer(Environment.getExternalStorageDirectory() + "/output.mp4", MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
}
public void encode(byte[] data) {
long presentationTimeUs = System.nanoTime() / 1000;
ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1);
if (inputBufferIndex >= 0) {
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
inputBuffer.clear();
inputBuffer.put(data);
mediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, presentationTimeUs, 0);
}
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
while (outputBufferIndex >= 0) {
ByteBuffer outputBuffer = mediaCodec.getOutputBuffers()[outputBufferIndex];
if (!isMuxerStarted) {
MediaFormat outputFormat = mediaCodec.getOutputFormat();
trackIndex = mediaMuxer.addTrack(outputFormat);
mediaMuxer.start();
isMuxerStarted = true;
}
mediaMuxer.writeSampleData(trackIndex, outputBuffer, bufferInfo);
mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
}
}
public void release() {
mediaCodec.stop();
mediaCodec.release();
mediaMuxer.stop();
mediaMuxer.release();
}
}
```
这个类使用MediaCodec API对视频进行编码,并使用MediaMuxer API将编码后的视频写入文件。
在你的Activity中,你可以使用Camera API或其他方法来捕获视频帧,并将它们传递给VideoEncoder对象进行编码和保存。以下是使用Camera API捕获视频帧并将它们传递给VideoEncoder对象的示例代码:
```
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
public class MainActivity extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback {
private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;
private static final String TAG = "MainActivity";
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private VideoEncoder videoEncoder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
openCamera();
try {
videoEncoder = new VideoEncoder();
} catch (IOException e) {
Log.e(TAG, "Failed to create VideoEncoder", e);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
videoEncoder.release();
}
private void openCamera() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
} else {
camera = Camera.open();
try {
camera.setPreviewDisplay(surfaceHolder);
camera.setPreviewCallback(this);
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
int bufferSize = size.width * size.height * 3 / 2;
camera.addCallbackBuffer(new byte[bufferSize]);
camera.startPreview();
} catch (IOException e) {
Log.e(TAG, "Failed to start preview", e);
}
}
}
private void releaseCamera() {
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (videoEncoder != null) {
videoEncoder.encode(data);
}
camera.addCallbackBuffer(data);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}
}
}
}
```
在这个示例中,MainActivity类使用SurfaceView来显示摄像头预览,并使用Camera API来捕获视频帧。当收到预览帧时,它将它们传递给VideoEncoder对象进行编码和保存。
请注意,这只是一个基本示例,你需要根据你的需求进行修改和扩展。
阅读全文