2017-10-14 102 views
1

我正在開發一個Android應用程序,它在應用程序中記錄視頻。 它很好地記錄了視頻並保存在文件中。但開始預覽功能失敗,並且在錄製過程中我沒有預覽。Android相機記錄不錯,但開始預覽失敗

這是代碼:

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) { 

     } 


    } 

,因爲我在互聯網上最例子所看到的,startpreview函數調用上surfaceChanged事件:

@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(); 

    } 
} 

回答

0

嘗試setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)爲您的相機SurfaceView

+1

持有我已經在使用的onCreate它活動()事件。 – siavash