实现录像的时候一直没有调用start方法,导致会话建立却没开始录像,数据一直没有写到本地的mp4文件。需要注意!
最近在忙毕业设计所以有关说明还要晚点。
package com.example.camera2;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.FileUtils;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CAMERA_CODE = 100;
private CameraCaptureSession cameraCaptureSession;
private Handler mainHandler,childHandler;
private SurfaceView mSurfaceView;
private CameraManager cameraManager;
private String mCameraID;
private ImageReader imageReader;
private CameraDevice mCameraDevice;
private SurfaceHolder mSurfaceHolder;
private Image image;
private ImageView iv_show;
private MediaRecorder mrecord;
private Size mVideoSize;
private CaptureRequest.Builder previewRequestBuilder;
private String mNextVideoAbsolutePath;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();//??????
///为了照片竖直显示
static {
ORIENTATIONS.append(Surface.ROTATION_0,90);
ORIENTATIONS.append(Surface.ROTATION_90,0);
ORIENTATIONS.append(Surface.ROTATION_180,270);
ORIENTATIONS.append(Surface.ROTATION_270,180);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button take_picture=findViewById(R.id.snapshot);
final Button recoring=findViewById(R.id.recording);
initView();
take_picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takepicture();
}
});
recoring.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
Button b=(Button)v;
switch (b.getText().toString()){
case "recording":
try {
startrecord();
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
b.setText("stop");
break;
case "stop":
try {
stoprecord();
} catch (CameraAccessException e) {
e.printStackTrace();
}
b.setText("recording");
break;
}
}
});
}
private CameraDevice.StateCallback stateCallback=new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
mCameraDevice=camera;
try {
preview();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
if(mCameraDevice!=null){
mCameraDevice.close();
}
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
}
};
private void initView(){
iv_show=(ImageView)findViewById(R.id.imageView);
mSurfaceView=findViewById(R.id.surfaceView);
mSurfaceHolder=mSurfaceView.getHolder();
mSurfaceHolder.setKeepScreenOn(true);
mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void surfaceCreated(SurfaceHolder holder) {
initcamera();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(mCameraDevice!=null){
mCameraDevice.close();;
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void initcamera(){
HandlerThread handlerThread=new HandlerThread("Camera2");
handlerThread.start();
childHandler=new Handler(handlerThread.getLooper());//关联handlerThread的looper对象实现消息处理操作
mainHandler=new Handler(Looper.getMainLooper());//获取主线程的LOOPER
mCameraID=""+CameraCharacteristics.LENS_FACING_FRONT;
imageReader=ImageReader.newInstance(1080,1920, ImageFormat.JPEG,1);
imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {///??????????
@Override
public void onImageAvailable(ImageReader reader) {
image=imageReader.acquireLatestImage();
ByteBuffer buffer=image.getPlanes()[0].getBuffer();//这里的0未知
byte[] bytes=new byte[buffer.remaining()];//remaining 目前的缓存位置和容量
buffer.get(bytes);//由缓冲区写入字节数组
final Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);//转化为位图
final Bitmap bit=rotateBitmap(bitmap,90);
if(bit!=null){
writeToFile(bit);
iv_show.setImageBitmap(bit);
image.close();
}
}
},mainHandler);
cameraManager = (CameraManager)MainActivity.this.getSystemService(Context.CAMERA_SERVICE);
try{
if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_CAMERA_CODE);
}else{
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(mCameraID);
StreamConfigurationMap map = characteristics
.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));//这一段
cameraManager.openCamera(mCameraID,stateCallback,mainHandler);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void preview() throws CameraAccessException {
previewRequestBuilder=mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
previewRequestBuilder.addTarget(mSurfaceHolder.getSurface());//addTarget(Surface)方法附着到对应的Surface上显示
mCameraDevice.createCaptureSession(Arrays.asList(mSurfaceHolder.getSurface(), imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {//开始处理拍照等请求
if( mCameraDevice==null)return;
cameraCaptureSession=session;
try{
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
CaptureRequest previewRequest=previewRequestBuilder.build();
cameraCaptureSession.setRepeatingRequest(previewRequest,null,childHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
Toast.makeText(MainActivity.this,"配置失败",Toast.LENGTH_SHORT).show();
}
},childHandler);
}
private void takepicture(){
if(mCameraDevice==null)return;
final CaptureRequest.Builder captureResquestBuilder;
try{
captureResquestBuilder=mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureResquestBuilder.addTarget(imageReader.getSurface());
captureResquestBuilder.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureResquestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
int rotation=MainActivity.this.getWindowManager().getDefaultDisplay().getRotation();
captureResquestBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));//????
CaptureRequest mCaptureRequest=captureResquestBuilder.build();
cameraCaptureSession.capture(mCaptureRequest,null,childHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void writeToFile(Bitmap bitmap){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
//上面是日期生成
File file=new File(getExternalCacheDir(),simpleDateFormat.format(date)+".jpg");
if(file.exists()){
file.delete();
}
try{
OutputStream os=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,os);
Toast.makeText(MainActivity.this,"保存成功位置"+getExternalCacheDir()+"/"+simpleDateFormat.format(date)+".jpg",Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
if (degrees == 0 || null == bitmap) {
return bitmap;
}
Matrix matrix = new Matrix();
matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmp;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void initrecord() throws IOException {
mrecord=new MediaRecorder();//初始化录像
mrecord.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecord.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mrecord.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
// mNextVideoAbsolutePath = FileUtils.createVideoDiskFile(appContext, FileUtils.createVideoFileName()).getAbsolutePath();
if (mNextVideoAbsolutePath == null || mNextVideoAbsolutePath.isEmpty()) {
mNextVideoAbsolutePath = getVideoFilePath(MainActivity.this);
}
mrecord.setOutputFile(mNextVideoAbsolutePath);
mrecord.setVideoEncodingBitRate(10000000);
mrecord.setVideoFrameRate(30);//帧数
mrecord.setVideoSize(mVideoSize.getWidth(),mVideoSize.getHeight());
mrecord.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mrecord.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mrecord.prepare();
}
private void closePreviewSession() {
if (cameraCaptureSession != null) {
cameraCaptureSession.close();
cameraCaptureSession = null;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startrecord() throws CameraAccessException, IOException {
final CaptureRequest.Builder recordRequestBuilder=mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
initrecord();
List<Surface> surfaces = new ArrayList<>();//mSurfaceHolder.getSurface()
surfaces.add(mSurfaceHolder.getSurface());
recordRequestBuilder.addTarget(mSurfaceHolder.getSurface());
Surface recorderSurface=mrecord.getSurface();
surfaces.add(recorderSurface);
recordRequestBuilder.addTarget(recorderSurface);
mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
cameraCaptureSession=session;
try {
recordRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
cameraCaptureSession.setRepeatingRequest(recordRequestBuilder.build(),null,childHandler);
mrecord.start();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
}
},childHandler);
}
private String getVideoFilePath(Context context) {//获取路径函数
final File dir = context.getExternalFilesDir(null);
return (dir == null ? "" : (dir.getAbsolutePath() + "/"))
+ System.currentTimeMillis() + ".mp4";
}
private void stoprecord() throws CameraAccessException {
if(mrecord!=null){
try {
mrecord.stop();
}catch (IllegalStateException e){
mrecord=null;
mrecord=new MediaRecorder();
}
mrecord.release();
mrecord=null;
}
}
private static Size chooseVideoSize(Size[] choices) {
for (Size size : choices) {
if (size.getWidth() == size.getHeight() * 4 / 3 && size.getWidth() <= 1080) {
return size;
}
}
//Log.e(TAG, "Couldn't find any suitable video size");
return choices[choices.length - 1];
}
}