2

I have to record the video from the front camera only, I Googled a lot, but have not been able to find a solution (simple)

if i set the cameratype to 1, the app crashes ..

here is my code

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
    MediaRecorder recorder;
    SurfaceHolder holder;
    boolean recording = false;
    String pathVideo;
    private int cameraType = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      /*  requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
               WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); */

        pathVideo = "/reg_" + System.currentTimeMillis() + ".mp4";
        recorder = new MediaRecorder();
        initRecorder();
        setContentView(R.layout.camera);

        SurfaceView cameraView = (SurfaceView) findViewById(R.id.surface_camera);
        holder = cameraView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);



        Button rec =(Button) findViewById(R.id.buttonstart);
        rec.setOnClickListener(new OnClickListener() {
            public void onClick(View v)
            {
                  if (recording) {
                      recorder.stop();
                      recording = false;
                      recorder.release();
                      // Let's initRecorder so we can record again
                    initRecorder();
                    prepareRecorder();
                  } else {
                      recording = true;
                      recorder.start();
                  }
            } 
         });
    }

    private void initRecorder() {

        recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        CamcorderProfile cpHigh = CamcorderProfile
                .get(CamcorderProfile.QUALITY_HIGH);
        recorder.setProfile(cpHigh);


          File Directory = new File("/sdcard/CantaTu/");
       // have the object build the directory structure, if needed.
       Directory.mkdirs();
       File mediaFile = new File(Directory,pathVideo);

        if(mediaFile.exists()){
         mediaFile.delete();
        }
        recorder.setOutputFile(mediaFile.getAbsolutePath());
        recorder.setMaxDuration(400000); // 50 seconds
        recorder.setMaxFileSize(50000000); // Approximately 5 megabytes
    }

    private void prepareRecorder() {
        recorder.setPreviewDisplay(holder.getSurface());

        try {

            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            finish();
        } catch (IOException e) {
            e.printStackTrace();
            finish();
        }
    }



    public void surfaceCreated(SurfaceHolder holder) {
        //camera = Camera.open(cameraType);
        prepareRecorder();
    }

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

    public void surfaceDestroyed(SurfaceHolder holder) {
        if (recording) {
            recorder.stop();
            recording = false;
            recorder.release();
        }
        recorder.release();
        //finish();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

there're no way to simply recordo to the front camera? thank's!

EDIT

This is my actual code (and it don't work if i try to open front camera)

      public void inizializzazione(){

          cameraView.setVisibility(0);


          boolean found = false;
             int i;

             for(i=0; i< Camera.getNumberOfCameras(); i++){
                 System.out.println("camera n " +i);
                 Camera.CameraInfo newInfo = new Camera.CameraInfo();
                 Camera. getCameraInfo(i, newInfo);

                 if (newInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                     try {
                         found = true;
                        cam = Camera.open(i);
                        System.out.println("trovata la fotocamera frontale");
                     } catch (RuntimeException e) {
                         Log.e("Your_TAG", "Camera failed to open: " + e.getLocalizedMessage());
                     }


             }



            pathVideo = "/reg_" + System.currentTimeMillis() + ".mp4";
          File Directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/CantaTu/");
           // have the object build the directory structure, if needed.
           Directory.mkdirs();
           File mediaFile = new File(Directory,pathVideo);

            if(mediaFile.exists()){
             mediaFile.delete();
            }



            recorder = new MediaRecorder();

             holder = cameraView.getHolder();
             holder.addCallback(this);
             holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 

            recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            recorder.setVideoSource(1);

             CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

            recorder.setProfile(cpHigh);

             recorder.setOutputFile(mediaFile.getAbsolutePath());
             recorder.setMaxDuration(400000); // 50 seconds

             recorder.setPreviewDisplay(holder.getSurface());




             try {
                 if(found == true){
                     recorder.setCamera(cam);
                 } 
                recorder.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             recorder.start();

             scritta.setVisibility(0);
             caricamento.setVisibility(4);





      }

}

i have no idea why it don't open the front camera... The error is "start called in an invalid state" (Because it found the front camera, and try to set)

Lele
  • 703
  • 3
  • 15
  • 34
  • There are some special situations to take care of; like, *Nexus 7* and some other devices may only have a front-facing camera. Even though there is only one camera, you still are required to explicitly choose it by `id`. See also http://stackoverflow.com/questions/12010383/nexus-7-support-for-android-application-manifest-assembly – Alex Cohn Jul 06 '13 at 12:59
  • i think's the problem's isn't n the manifest, because the front camera work exactly... i set android:required="false" on camera permision – Lele Jul 06 '13 at 13:07

2 Answers2

4

You need to find the id of the front camera. To do that, go

boolean found = false;
int i;
for (i=0; i< Camera.getNumberOfCameras(); i++) {
    Camera.CameraInfo newInfo = new Camera.CameraInfo();
    Camera.getCameraInfo(i, newInfo);
    if (newInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
        found = true;
        break;
    }
}

If found is true, i is the front camera id. Then you need to open that camera and pass it in

recorder.setCamera(Camera.open(i));
Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • thak's, there're an error on if(newInfo.facing == CAMERA_FACING_FRONT CAMERA_FACING_FRONT is a simple string? – Lele Jul 06 '13 at 12:38
  • i try with "1" but don't work on recorder.setCamera(Camera.open(i)); java.illegalStateException i've inserted your code in initRecorder(), is correct? – Lele Jul 06 '13 at 12:45
  • should be `CameraInfo.CAMERA_FACING_FRONT`. – Alex Cohn Jul 06 '13 at 12:47
  • is newInfo.CAMERA_FACING_FRONT but it return true this is correct? if(found == true){ recorder.setCamera(Camera.open(i)); } recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); CamcorderProfile cpHigh = CamcorderProfile .get(CamcorderProfile.QUALITY_HIGH); recorder.setProfile(cpHigh); the error in on setProfile – Lele Jul 06 '13 at 12:54
  • @Lele: it could be that the front facing camera does not support `QUALITY_HIGH`. Which device do you test, and which system version? – Alex Cohn Jul 06 '13 at 12:57
  • i'm testing on a tablet with 2 mp front camera there're a way to set the max quality supported from the camera? – Lele Jul 06 '13 at 13:00
  • uhm now i'm setting video quality on Low, and QUALITY_480P but i've an error on the prepare() – Lele Jul 06 '13 at 13:09
  • @Lele: *i've an error on the prepare()*: would you like to be more specific? What is the exception, what does logcat show? – Alex Cohn Jul 06 '13 at 13:17
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/32998/discussion-between-alex-cohn-and-lele) – Alex Cohn Jul 06 '13 at 13:19
  • Sorry to bump this! For those arriving here looking for an answer, make certain you are using ```CamcorderProfile.hasProfile(int,int)``` _as well as_ using ```CamcorderProfile.get(int,int)```. Failure to use both will result in getting the wrong profile. The default for both methods is to check/get the profile for the first back-facing camera. TL;DR you must use the camera id for both checking (```hasProfile```) as well getting (```get```). – BK- Feb 01 '16 at 21:07
1

it's too late to be answered but i ran into same problem and then finally I found out the problem on stack. You can set high profile for the back camera.

//For Front Camera
     CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

but you can't set high profile for the front camera. I used 480P in my case like

//For back camera
     CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);

you can find details at this post. Android can't record video with Front Facing Camera, MediaRecorder start failed: -19

Community
  • 1
  • 1
Awais Ahmad
  • 427
  • 3
  • 17