本文介绍了试图切换回相机前面,但得到的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图切换回相机前面,但得到的异常。找不到 这个问题请检查并帮助..

我的code: -

 公共类AndroidVideoCapture延伸活动{
    私有静态最后字符串变量=CameraRecorderActivity;
  私人相机myCamera;
    私人MyCameraSurfaceView myCameraSurfaceView;
    私人MediaRecorder mediaRecorder;
    私有静态字符串VAL =是;
    私人按钮useOtherCamera;
  按钮myButton的;
  SurfaceHolder surfaceHolder;
  布尔记录;

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        记录= FALSE;
        的setContentView(R.layout.activity_android_video_capture);
        useOtherCamera =(按钮)findViewById(R.id.useOtherCamera);
        useOtherCamera.setOnClickListener(
                新View.OnClickListener(){
                    @覆盖
                     公共无效的onClick(视图v){
            //获取相机为preVIEW
            myCamera = getCameraInstance();
        }
        });
        的FrameLayout myCamera preVIEW =(的FrameLayout)findViewById(R.id.videoview);
        myCamera preview.addView(myCameraSurfaceView);
        为myButton =(按钮)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
        myButton.setOnClickListener(myButtonOnClickListener);

        如果(myCamera == NULL){
            的System.out.println(打印TRACK  -  7);
         Toast.makeText(AndroidVideoCapture.this,
           轮不到相机,
           Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView =新MyCameraSurfaceView(这一点,myCamera);
        }

    Button.OnClickListener myButtonOnClickListener
    =新Button.OnClickListener(){

  @覆盖
  公共无效的onClick(视图v){
   // TODO自动生成方法存根
   如果(录音){
                //停止录制并发行摄像头
                mediaRecorder.stop(); //停止录制
                releaseMediaRecorder(); //释放MediaRecorder对象

                //保存退出后,
                完();
   }其他{

    //发布MediaRecorder开始前摄像头
    releaseCamera();

          如果(!prepareMediaRecorder()){
           Toast.makeText(AndroidVideoCapture.this,
             在失败prepareMediaRecorder()\ N  - !结束 - ,
             Toast.LENGTH_LONG).show();
           完();
          }

    mediaRecorder.start();
    记录= TRUE;
    myButton.setText(STOP);
   }
  }};

  公众诠释getFrontCameraId(){
      CameraInfo CI =新CameraInfo();
      的for(int i = 0; I< Camera.getNumberOfCameras();我++){
          Camera.getCameraInfo(I,CI);
          如果((VAL ==是)及及(ci.facing == CameraInfo.CAMERA_FACING_FRONT))
          {
              VAL =无;
              返回我;
          }

      }

      返回CameraInfo.CAMERA_FACING_BACK; //没有前置摄像头发现
  }
    公共相机getCameraInstance(){
  // TODO自动生成方法存根
        相机C = NULL;
        尝试 {
          INT指数= getFrontCameraId();
          如果(索引!= -1)
          {
           C = Camera.open(指数);
         // C = Camera.open(); //尝试获取摄像头实例
        }其他{
             C = Camera.open(指数);
        }
        }
        赶上(例外五){
          Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
            //相机无法使用(使用或不存在)
        }
        返回℃; //如果相机是不可用,则返回null
  }

  私人布尔prepareMediaRecorder(){
     myCamera = getCameraInstance();
     mediaRecorder =新MediaRecorder();

     myCamera.unlock();
     mediaRecorder.setCamera(myCamera);

     mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
     mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

     mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));

     mediaRecorder.setOutputFile(/ SD卡/ myvideo.mp4);
        mediaRecorder.setMaxDuration(60000); //设置最大持续时间60秒。
        mediaRecorder.setMaxFileSize(5000000); //设置最大文件大小为5M

     mediaRecorder.set previewDisplay(myCameraSurfaceView.getHolder()getSurface());

     尝试 {
         mediaRecorder prepare()。
     }赶上(IllegalStateException异常E){
         releaseMediaRecorder();
         Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
         返回false;
     }赶上(IOException异常E){
         releaseMediaRecorder();
         Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
         返回false;
     }
     返回true;

  }

    @覆盖
    保护无效的onPause(){
        super.onPause();
        releaseMediaRecorder(); //如果您使用的是MediaRecorder,先将它
        releaseCamera(); //在暂停时立即松开相机
    }

    私人无效releaseMediaRecorder(){
        如果(mediaRecorder!= NULL){
            mediaRecorder.reset(); //清晰的记录配置
            mediaRecorder.release(); //释放录像机对象
            mediaRecorder = NULL;
            myCamera.lock(); //锁定相机以备后用
        }
    }

    私人无效releaseCamera(){
        如果(myCamera!= NULL){
            myCamera.release(); //释放相机用于其它应用
            myCamera = NULL;
        }
    }

  公共类MyCameraSurfaceView扩展了SurfaceView实现SurfaceHolder.Callback {

  私人SurfaceHolder mHolder;
     私人相机mCamera;

  公共MyCameraSurfaceView(上下文的背景下,相机摄像头){
         超(上下文);
         mCamera =摄像头;

         //安装SurfaceHolder.Callback所以我们得到通知时,该
         //下垫面创建和销毁。
         mHolder = getHolder();
         mHolder.addCallback(本);
         //德precated设置,但在Android上之前的版本3.0所需
         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
     }

  @覆盖
  公共无效surfaceChanged(SurfaceHolder持有人,INT格式,诠释权重,
    INT高度){
         //如果你的preVIEW可以改变或旋转,把这些事件的关心在这里。
         //确保调整或重新格式化之前停止preVIEW。

         如果(mHolder.getSurface()== NULL){
           // preVIEW表面不存在
           返回;
         }

         在进行更改之前//停止preVIEW
         尝试 {
             mCamera.stop preVIEW();

         }赶上(例外五){
           Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
           //忽略:试图阻止一个不存在的preVIEW
         }

         //做任何调整大小,旋转或重新格式化这里的变化

         //启动preVIEW使用新设置
         尝试 {
             mCamera.set previewDisplay(mHolder);
             mCamera.start preVIEW();

         }赶上(例外五){
           Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
         }
  }

  @覆盖
  公共无效surfaceCreated(SurfaceHolder持有者){
   // TODO自动生成方法存根
   //表面有被创建,现在告诉相机在哪里画preVIEW。
         尝试 {
             mCamera.set previewDisplay(保持器);
             mCamera.start preVIEW();
         }赶上(IOException异常E){
           Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
         }
  }

  @覆盖
  公共无效surfaceDestroyed(SurfaceHolder持有者){
   // TODO自动生成方法存根

  }
  }
  }
 

解决方案

切换到其他前停止拍照previous例如:

 如果(相机!= NULL){
        camera.stop preVIEW();
        camera.set previewCallback(空);
        camera.release();
        摄像头= NULL;
        surfaceholder.removeCallback(CameraActivity.this);
        surfaceholder = NULL;
}
 

和完成当前摄像头的活动,呼吁启动相同的摄像头活动的意图。

Trying to switch camera back to front but getting exception. cant find the problem Please Check and help..

My Code:-

 public class AndroidVideoCapture extends Activity{
    private static final String TAG = "CameraRecorderActivity";
  private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;
    private static String val="yes";
    private Button useOtherCamera;
  Button myButton;
  SurfaceHolder surfaceHolder;
  boolean recording;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recording = false;
        setContentView(R.layout.activity_android_video_capture);
        useOtherCamera = (Button) findViewById(R.id.useOtherCamera);
        useOtherCamera.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                     public void onClick(View v) {
            //Get Camera for preview
            myCamera = getCameraInstance();
        }
        });
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        myCameraPreview.addView(myCameraSurfaceView);
        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
        myButton.setOnClickListener(myButtonOnClickListener);

        if(myCamera == null){
            System.out.println("PRINT TRACK--7 ");
         Toast.makeText(AndroidVideoCapture.this,
           "Fail to get Camera",
           Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        }

    Button.OnClickListener myButtonOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   if(recording){
                // stop recording and release camera
                mediaRecorder.stop();  // stop the recording
                releaseMediaRecorder(); // release the MediaRecorder object

                //Exit after saved
                finish();
   }else{

    //Release Camera before MediaRecorder start
    releaseCamera();

          if(!prepareMediaRecorder()){
           Toast.makeText(AndroidVideoCapture.this,
             "Fail in prepareMediaRecorder()!\n - Ended -",
             Toast.LENGTH_LONG).show();
           finish();
          }

    mediaRecorder.start();
    recording = true;
    myButton.setText("STOP");
   }
  }};

  public int getFrontCameraId() {
      CameraInfo ci = new CameraInfo();
      for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
          Camera.getCameraInfo(i, ci);
          if ((val=="yes") && (ci.facing == CameraInfo.CAMERA_FACING_FRONT))
          {
              val="no";
              return i;
          }

      }

      return CameraInfo.CAMERA_FACING_BACK; // No front-facing camera found
  }
    public Camera getCameraInstance(){
  // TODO Auto-generated method stub
        Camera c = null;
        try {
          int index = getFrontCameraId();
          if (index != -1)
          {
           c = Camera.open(index);
         //   c = Camera.open(); // attempt to get a Camera instance
        }else{
             c = Camera.open(index);
        }
        }
        catch (Exception e){
          Log.d(TAG, "Error setting camera preview: " + e.getMessage());
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
  }

  private boolean prepareMediaRecorder(){
     myCamera = getCameraInstance();
     mediaRecorder = new MediaRecorder();

     myCamera.unlock();
     mediaRecorder.setCamera(myCamera);

     mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
     mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

     mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));

     mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
        mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
        mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M

     mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

     try {
         mediaRecorder.prepare();
     } catch (IllegalStateException e) {
         releaseMediaRecorder();
         Log.d(TAG, "Error setting camera preview: " + e.getMessage());
         return false;
     } catch (IOException e) {
         releaseMediaRecorder();
         Log.d(TAG, "Error setting camera preview: " + e.getMessage());
         return false;
     }
     return true;

  }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

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

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();        // release the camera for other applications
            myCamera = null;
        }
    }

  public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

  private SurfaceHolder mHolder;
     private Camera mCamera;

  public MyCameraSurfaceView(Context context, Camera camera) {
         super(context);
         mCamera = camera;

         // Install a SurfaceHolder.Callback so we get notified when the
         // underlying surface is created and destroyed.
         mHolder = getHolder();
         mHolder.addCallback(this);
         // deprecated setting, but required on Android versions prior to 3.0
         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
     }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int weight,
    int height) {
         // If your preview can change or rotate, take care of those events here.
         // Make sure to stop the preview before resizing or reformatting it.

         if (mHolder.getSurface() == null){
           // preview surface does not exist
           return;
         }

         // stop preview before making changes
         try {
             mCamera.stopPreview();

         } catch (Exception e){
           Log.d(TAG, "Error setting camera preview: " + e.getMessage());
           // ignore: tried to stop a non-existent preview
         }

         // make any resize, rotate or reformatting changes here

         // start preview with new settings
         try {
             mCamera.setPreviewDisplay(mHolder);
             mCamera.startPreview();

         } catch (Exception e){
           Log.d(TAG, "Error setting camera preview: " + e.getMessage());
         }
  }

  @Override
  public void surfaceCreated(SurfaceHolder holder) {
   // TODO Auto-generated method stub
   // The Surface has been created, now tell the camera where to draw the preview.
         try {
             mCamera.setPreviewDisplay(holder);
             mCamera.startPreview();
         } catch (IOException e) {
           Log.d(TAG, "Error setting camera preview: " + e.getMessage());
         }
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder holder) {
   // TODO Auto-generated method stub

  }
  }
  }
解决方案

Stop the camera previous instance before switching to other :

if (camera != null) {
        camera.stopPreview();
        camera.setPreviewCallback(null);
        camera.release();
        camera = null;
        surfaceholder.removeCallback(CameraActivity.this);
        surfaceholder = null;
}

And finish current camera activity, call start intent of same camera activity.

这篇关于试图切换回相机前面,但得到的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:29