Android Camera记录良好,但startPreview失败

时间:2017-10-14 15:46:09

标签: android video camera mediarecorder

我正在开发一款在应用内录制视频的Android应用。 它可以很好地记录视频并保存在文件中。但是startpreview功能失败,我在录制过程中没有预览。

这是代码:

private  void startVRec(){
        //final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
        try {

            vrec = new MediaRecorder();
            mCamera = Camera.open();
             params = mCamera.getParameters();
            Camera.Size size=getOptimalPreviewSize(params.getSupportedPreviewSizes(), 240, 240);
            params.setPreviewSize(size.height, size.width);
            mCamera.setParameters(params);
            vrec.setPreviewDisplay(surfaceHolder.getSurface());
           mCamera.unlock();
            vrec.setCamera(mCamera);
            camera_layout.setVisibility(View.VISIBLE);
            surfaceView.setVisibility(View.VISIBLE);
        } catch (Exception e) {

        }


    }

正如我在互联网上的大多数示例中看到的那样,在surfaceChanged事件上调用startpreview函数:

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

            //Camera.Size previewSize=null;
            try {

                if (mCamera != null)
                {
                    Camera.Size 
                   size=getOptimalPreviewSize(params.getSupportedPreviewSizes(), 240, 240);
                    params.setPreviewSize(size.height, size.width);
                    mCamera.setParameters(params);
                    mCamera.startPreview();
                }
            } catch (Exception e) {
                Toast.makeText(activity, "error "+ e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

它开始在surfaceCreated事件上录制

public void surfaceCreated(SurfaceHolder holder){         if(mCamera!= null){

        try {

            vrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            vrec.setAudioSource(MediaRecorder.AudioSource.MIC);
            vrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            vrec.setVideoFrameRate(30);
            vrec.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
            vrec.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            vrec.setPreviewDisplay(surfaceHolder.getSurface());
            vrec.setOutputFile(FileBackend.getConversationsImageDirectory() + System.currentTimeMillis() + ".mp4");
            vrec.prepare();

            vrec.start();

        }
       catch(IllegalStateException e2){
                Toast.makeText(activity,"err cam stop ill :"+ e2.getMessage(),Toast.LENGTH_LONG).show();
            }

         catch (Exception e) {
            Toast.makeText(activity,"err surface created :"+ e.getMessage(),Toast.LENGTH_LONG).show();
        }

    }
    else {
        Toast.makeText(activity, "Camera not available!", Toast.LENGTH_LONG).show();

    }
}

1 个答案:

答案 0 :(得分:0)

尝试setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)为您的相机SurfaceView

持有人