camera2录像的实现

实现录像的时候一直没有调用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];
    }


}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,539评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,911评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,337评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,723评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,795评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,762评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,742评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,508评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,954评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,247评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,404评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,104评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,736评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,352评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,557评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,371评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,292评论 2 352