开始捕获视频后,Android MediaRecorder预览大小发生了变化

时间:2016-05-11 15:16:41

标签: android camera preview mediarecorder

我正在开发一个允许用户捕捉视频的相机应用程序,我开始关注一些教程。 但问题是当我按下Capture视频按钮开始录制时,预览就会被拉伸 Before

After press record button

这是我的代码:

package com.example.phuongnguyen.cameraz;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MainActivity extends Activity implements SurfaceHolder.Callback {

    Camera mCamera;
    Button btnCapture;
    Button btnSwitch;
    Button btnRecord;
    SurfaceHolder surfaceHolder;
    int cameraID;
    private PreviewSurfaceView mOpenCvCameraView;
    private DrawingView drawingView;

    static MediaRecorder mediaRecorder;
    boolean recording;
    String RECORD = "Record \nvideo";
    String STOP_RECORD = "Stop";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createImageGallary();

        btnCapture = (Button) findViewById(R.id.captureImage);
        btnSwitch = (Button) findViewById(R.id.button_switch);
        btnRecord = (Button) findViewById(R.id.button_record);

        mOpenCvCameraView = (PreviewSurfaceView) findViewById(R.id.surfaceView);
        mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
        mOpenCvCameraView.setListener(this);

        drawingView = (DrawingView) findViewById(R.id.drawing_view);
        mOpenCvCameraView.setDrawingView(drawingView);

        surfaceHolder = mOpenCvCameraView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                captureImage();
            }
        });

        btnSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchCamera();
            }
        });

        mediaRecorder = new MediaRecorder();


        recording = false;
        //initMediaRecorder();

        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(recording){
                    mediaRecorder.stop();
                    releaseMediaRecorder();
                    btnRecord.setText(RECORD);
                    recording = false;
                    //finish();
                }else{
                    //refreshCamera();
                    //MediaRecorder test = mediaRecorder;

                    try {
                        initMediaRecorder();
                        mediaRecorder.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    recording = true;
                    btnRecord.setText(STOP_RECORD);
                }
            }
        });

    }

    private void initMediaRecorder(){

        //mediaRecorder.setVideoSize(mOpenCvCameraView.getWidth(), mOpenCvCameraView.getHeight());
        mCamera.unlock();
        mediaRecorder.setCamera(mCamera);
        //mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(cameraID, CamcorderProfile.QUALITY_HIGH);
        mediaRecorder.setProfile(camcorderProfile_HQ);
        //mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
        mediaRecorder.setMaxDuration(5000); // Set max duration 5 sec.
        mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
        if(cameraID == Camera.CameraInfo.CAMERA_FACING_BACK){
            mediaRecorder.setOrientationHint(90);
        }else{
            mediaRecorder.setOrientationHint(270);
        }




        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
           e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void prepareMediaRecorder(){
        mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            //e.printStackTrace();
        } catch (IOException e) {
            releaseMediaRecorder();
            //e.printStackTrace();
        }
    }

    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.reset(); // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            //mCamera.lock(); // lock camera for later use
        }
    }

    private String GALLARY_LOCATION_NAME = "Camera Z";
    File galleryFolder;
    private void createImageGallary(){
        File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        galleryFolder = new File(storageDirectory,GALLARY_LOCATION_NAME);
        if (!galleryFolder.exists()){
            galleryFolder.mkdirs();
        }
    }

    private String imagePath(File imageFile){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = simpleDateFormat.format(new Date());
        String photo = "CameraZ_"+date+".jpg";
        String file_name = imageFile.getAbsolutePath()+"/"+photo;
        return file_name;
    }

    Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            new BitmapAsyncTask(getApplicationContext(), imagePath(galleryFolder), cameraID, data).execute();

            //Toast.makeText(getApplicationContext(), "Picture saved : "+imagePath(gallaryFolder), Toast.LENGTH_SHORT).show();
            refreshCamera();
            //refreshGallery(photoFile);
        }
    };


    AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            btnCapture.setEnabled(true);
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        refreshCamera();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mOpenCvCameraView != null){
            releaseCamera();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mOpenCvCameraView != null){

        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            cameraID = Camera.CameraInfo.CAMERA_FACING_BACK;
        }catch (RuntimeException e){
            e.printStackTrace();
        }
        mediaRecorder.setPreviewDisplay(holder.getSurface());
        Camera.Parameters parameter = mCamera.getParameters();
        parameter.setPreviewFrameRate(20);
        parameter.setPreviewSize(mOpenCvCameraView.getWidth(), mOpenCvCameraView.getHeight());
        mCamera.setParameters(parameter);
        mCamera.setDisplayOrientation(90);

        try{
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        }catch (Exception e){

        }

        //prepareMediaRecorder();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        refreshCamera();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }


    public void switchCamera(){
        mCamera.stopPreview();
        mCamera.release();
        if(cameraID == Camera.CameraInfo.CAMERA_FACING_BACK){
            cameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
        }else{
            cameraID = Camera.CameraInfo.CAMERA_FACING_BACK;
        }

        try {
            mCamera = Camera.open(cameraID);
        }catch (RuntimeException e){

        }
        Camera.Parameters parameter = mCamera.getParameters();
        parameter.setPreviewFrameRate(20);
        parameter.setPreviewSize(mOpenCvCameraView.getWidth(), mOpenCvCameraView.getHeight());
        mCamera.setParameters(parameter);
        mCamera.setDisplayOrientation(90);

        try{
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        }catch (Exception e){

        }

    }

    public void captureImage(){
        mCamera.takePicture(null, null, pictureCallback);
    }

    public void refreshGallery( File file){
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        sendBroadcast(intent);
    }

    public void refreshCamera(){
        if(surfaceHolder.getSurface()== null){
            return;
        }
        try{
            mCamera.stopPreview();
        }catch (Exception e){

        }
        try{
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        }catch (Exception e){

        }
    }


    public void releaseCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    public void doTouchFocus(final Rect tfocusRect) {
        try {
            final List<Camera.Area> focusList = new ArrayList<Camera.Area>();
            Camera.Area focusArea = new Camera.Area(tfocusRect, 1000);
            focusList.add(focusArea);

            Camera.Parameters para = mCamera.getParameters();
            para.setFocusAreas(focusList);
            para.setMeteringAreas(focusList);
            mCamera.setParameters(para);

            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

0 个答案:

没有答案