This is my code:
package eye.sight.test;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
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.widget.Button;
public class AndroidVideoCapture extends Activity implements SurfaceHolder.Callback{
Button myButton;
MediaRecorder mediaRecorder;
SurfaceHolder surfaceHolder;
boolean recording;
Camera c;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recording = false;
setContentView(R.layout.main1);
initMediaRecorder();
SurfaceView myVideoView = (SurfaceView)findViewById(R.id.videoview);
surfaceHolder = myVideoView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
myButton = (Button)findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
}
private Button.OnClickListener myButtonOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(recording){
mediaRecorder.stop();
mediaRecorder.release();
finish();
}else{
mediaRecorder.start();
recording = true;
myButton.setText("STOP");
}
}};
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
prepareMediaRecorder();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
private void initMediaRecorder(){
mediaRecorder = new MediaRecorder();
// c.unlock();
// c = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
// mediaRecorder.setCamera(c);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
mediaRecorder.setProfile(camcorderProfile_HQ);
mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(60000);
//mediaRecorder.setMaxFileSize(5000000);
}
private void prepareMediaRecorder(){
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I've been googling around for quite a bit on how to use the front camera but no luck there whatsoever. What am I missing here? It works just fine on default but I'm unsure on when and how to use Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT); and Came.unlock();.
Thanks
Try doing this
private Camera FrontCamera()
{
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
Also add following in manifest file
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
Related
i'm developing an camera app which allows users to capture video, and i started following some tutorials.
But the problem is when i press the Capture video button to start recording, the preview is just stretched
Before
After press record button
This is my code:
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();
}
}
}
I have this camera app that previews alright but whenever I try to record it gives me an illegalstatexception like my MediaRecorder isn't setup properly but it is. I must note that I am using an emulator for this with both front and back cams emulated.
package l33trus.com.shite
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Calendar;
public class VideoCapture extends Fragment implements OnClickListener, SurfaceHolder.Callback ,MediaRecorder.OnInfoListener,Camera.PictureCallback
{
public static final String LOGTAG = "VIDEOCAPTURE";
private static final int PICTURE_SIZE_MAX_WIDTH = 0;
String[] varNames; // for reflection function
private MediaRecorder recorder;
private MediaPlayer mp;
private SurfaceHolder holder;
int cameraCount = 0;
private CamcorderProfile camcorderProfile;
//final MediaPlayer interfaceSounds;
Cvars varPtr; // static global variable class
private ImageView isRecordingView;
private boolean photoMode; // if not in photo mode it's in video mode
private Camera camera;
private Camera.Size mPreviewSize;
private ImageButton recordButton;
private RawCallback rawCallback;
private SurfaceView cameraView;
CameraInfo cameraInfo = new CameraInfo();
private int resid = 0;
private int cameraId;
String fileExtension = ".mp4";
private boolean recording = false;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private View currentView;
private LayoutInflater inflateTmp;
private boolean usecamera = true;
private boolean previewRunning = false;
private boolean paused = false;
#Override
public void onSaveInstanceState(Bundle state)
{
super.onSaveInstanceState(state);
}
public VideoCapture()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.videocapture, container, false);
recordButton = (ImageButton) rootView.findViewById(R.id.recordButton);
SurfaceView cameraView = (SurfaceView) rootView.findViewById(R.id.CameraView);
initRecorder();
holder = cameraView.getHolder();
holder.addCallback(this);
previewRunning = true;
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
recordButton.setOnClickListener(this);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
this.currentView = rootView;
this.inflateTmp = inflater;
return rootView;
}
private void initRecorder()
{
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile.get(cameraInfo.facing,CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
String fileName = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
recorder.setOutputFile(varPtr.DefaultStorageDir + fileName + ".mp4");
recorder.setMaxDuration(50000); // 50 seconds
}
private void prepareRecorder()
{
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
Toast toasty = Toast.makeText(this.getActivity(),"IllegalStateException prepareRecorder",Toast.LENGTH_LONG);
} catch (IOException e) {
e.printStackTrace();
Toast toasty = Toast.makeText(this.getActivity(),"IOException prepareRecorder",Toast.LENGTH_LONG);
}
}
public void onRecordStop() // handles manually stopping of the record and also called if it is closed when a tab or orientation is changed
{
recorder.stop();
recorder.release();
recording = false;
varPtr.recording = false;
isRecordingView.setImageResource(R.drawable.notrecordingimage);
recordButton.setImageResource(R.drawable.recording_button);
}
public void onRecordStart()
{
recording = true;
varPtr.recording = recording;
isRecordingView.setImageResource(R.drawable.recordingimage);
recordButton.setImageResource(R.drawable.record_stop_button);
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.recordButton:
if(photoMode)
{
//camera.takePicture(shutter,mPicture,new ImageCaptureCallback(this));
}
if (recording)
{
recorder.stop();
if (usecamera)
{
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
recorder.release();
prepareRecorder();
}
else
{
onRecordStart();
recorder.start();
Log.v(LOGTAG, "Recording Started");
}
recording ^= true;
varPtr.recording = recording;
break;
case R.id.CameraView:
break;
case R.id.photoToggleButton:
photoMode ^= true;
break;
case R.id.videoToggleButton:
photoMode ^= true;
break;
}
}
private Camera getCameraInstance()
{
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c;
}
private boolean checkCameraHardware(Context context)
{
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
// this device has a camera
return true;
}
else
{
// no camera on this device
return false;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
Log.v(LOGTAG, "surfaceCreated");
// configure(camera);
if(! checkCameraHardware(getActivity().getApplicationContext()))
{
getActivity().finish();
}
prepareRecorder();
try
{
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e)
{
Log.e(LOGTAG,e.getMessage());
e.printStackTrace();
} catch (NullPointerException e)
{
Log.e("WTF","This sucks");
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
Log.v(LOGTAG, "surfaceChanged");
if (!recording && usecamera)
{
try
{
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(p);
holder = cameraView.getHolder();
holder.addCallback(this);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e)
{
Log.e(LOGTAG,e.getMessage());
e.printStackTrace();
}
catch(NullPointerException e)
{
Log.e("WTF","I hate my life");
e.printStackTrace();
}
prepareRecorder();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
Log.v(LOGTAG, "surfaceDestroyed");
if (recording)
{
recorder.stop();
onRecordStop();
}
}
#Override
public void onPause()
{
super.onPause();
holder.removeCallback(this); //http://stackoverflow.com/questions/12411346/camera-is-null-when-the-surfacecreated-method-is-executed-for-second-time
camera.release();
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra)
{
}
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
}
}
here is what logcat says
start called in an invalid state: 4
1762-1762/com.L33TRUS.shite D/AndroidRuntime﹕ Shutting down VM
1762-1762/com.L33TRUS.shite W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409961f8)
1762-1762/com.L33TRUS.shite E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at l33trus.com.moment.Fragments.VideoCapture.onClick(VideoCapture.java:194)
fixed by sanitizing the file name like this
fileName = fileName.replaceAll(":", "~");
fileName = fileName.replaceAll(",","");
fileName = fileName.replaceAll(" ","_");
also made sure the dirs were created before opening the file via the mkdirs() call
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)
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));
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
I getting error when I open camera in front facing mode and start recording. The app crashes.
My code is the following:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
MediaRecorder m_recorder;
int MAX_TIME=5;
String m_path;
String stringPath = "/sdcard/samplevideo.3gp";
MediaRecorder videoRecorder;
Surface surface;
MediaRecorder mrec;
/** Called when the activity is first created.**/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
if(!previewing){
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int camNo = 0; camNo < Camera.getNumberOfCameras(); camNo++) {
CameraInfo camInfo = new CameraInfo();
Camera.getCameraInfo(camNo, camInfo);
//Toast.makeText(MainActivity.this, camNo, Toast.LENGTH_LONG).show();
if (camInfo.facing==(Camera.CameraInfo.CAMERA_FACING_FRONT)) {
camera = Camera.open(1);
}
}
try{
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(surfaceHolder);
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (camera != null){
try
{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("before MediaRecorder");
mrec = new MediaRecorder(); // Works well
System.out.println("after MediaRecorder");
camera.unlock();
System.out.println("after Unlock");
mrec.setCamera(camera);
System.out.println("setcamera");
mrec.setPreviewDisplay(surfaceHolder.getSurface());
System.out.println("setcamera1");
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
System.out.println("setcamera2");
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile("/sdcard/recordvideooutput.3gpp");
try {
System.out.println("before prepare");
mrec.prepare();
System.out.println("after prepare");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
}});
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
try {
camera.reconnect();
camera.unlock();
} catch (Exception e) {
// TODO: handle exception
}
mrec.start();
// TODO Auto-generated method stub
/*if(camera != null && previewing){
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}*/
}});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
I just got a Nexus 7 I'm trying to port some code to. The following line works with no problem on a Xoom running Ice Cream:
mCamera.startPreview();
It also works correctly on the Nexus 7, but it logs errors:
E/NvOmxCamera( 126): OMX_ERRORTYPE android::NvOmxCamera::getCameraStereoMode(NvxComponent*, NvOmxCameraUserStereoMode&): Error: invalid NVX mode 0.
E/NvOmxCamera( 126): OMX_ERRORTYPE android::NvOmxCamera::getCameraStereoModeAndCaptureInfo(NvxComponent*, NvOmxCameraUserStereoMode&, NVX_STEREOCAPTUREINFO&): getCameraStereoMode failed with 0x00000000
This is a problem because it also logs these errors once per frame when I execute the line
mCamera.takePicture(null, null, null, pictureCallback);
Since I'm taking 10 frames per second, this disturbs me, so I'd like to fix the errors. I've grepped through all the sources (android sdk and ndk) and the text for the above errors doesn't appear anywhere. I believe from a lot of googling that this is happening in Nvidia's implementation of OpenMax, where it seems to be tied to the parameter "nv-stereo-mode" which has possible values of "left", "right", or "stereo" (the Nexus 7 only has one camera, so I don't know why it would care about stereo camera modes, but whatever). I tried setting it to each of the legal values using, for example:
mParams = mCamera.getParameters();
mParams.set("nv-stereo-mode", "right");
mCamera.setParameters(mParams);
But, my log says:
E/NvOmxCameraSettingsParser( 126): Skipping non-standard parameter: nv-stereo-mode
This appears to be related to the source file nvomxcamerasettingsparser.cpp, which I can't find anywhere on the web. I don't really know where to go from here, I've grepped and googled for everything I could think of, so any help would be greatly appreaciated.
Try below code for you issue. I hope it will works fine.
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Record extends Activity implements SurfaceHolder.Callback,
MediaRecorder.OnInfoListener {
Button myButton;
MediaRecorder mediaRecorder;
SurfaceHolder surfaceHolder;
boolean recording;
Camera camera;
int mCount;
TextView msg;
boolean rec = false;
String fileName = "DamageVideo.mp4";
CountDownTimer timer;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recording = false;
mediaRecorder = new MediaRecorder();
initMediaRecorder();
setContentView(R.layout.record_view);
SurfaceView myVideoView = (SurfaceView) findViewById(R.id.videoview);
surfaceHolder = myVideoView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
myButton = (Button) findViewById(R.id.mybutton);
msg = (TextView) findViewById(R.id.txttimer);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myButton.setVisibility(View.GONE);
myButton.setClickable(false);
try {
if (recording) {
recording = false;
myButton.setClickable(true);
myButton.setVisibility(View.VISIBLE);
Intent intent = new Intent();
setResult(100, intent);
finish();
overridePendingTransition(R.anim.trans_right_in,
R.anim.trans_right_out);
mediaRecorder.stop();
mediaRecorder.release();
moveFile();
} else {
recording = true;
camera.stopPreview();
camera.release();
// myButton.setVisibility(View.GONE);
timer.start();
// myButton.setClickable(false);
mediaRecorder.start();
new CountDownTimer(21000, 1000) {
public void onTick(long millisUntilFinished) {
msg.setText(+(22000 - (millisUntilFinished - 0))
/ 1000 + "/20");
}
public void onFinish() {
// msg.setText("10/10");
}
}.start();
myButton.setText("STOP");
// camera.release();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
timer = new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
myButton.setVisibility(View.VISIBLE);
myButton.setClickable(true);
}
};
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
try {
prepareMediaRecorder();
camera = Camera.open();
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
private void initMediaRecorder() {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
mediaRecorder.setProfile(camcorderProfile_HQ);
// mediaRecorder.setVideoFrameRate(30);
// File dir = Const.getFilePath();
File dir = Environment.getExternalStorageDirectory();
// String fname = "DamageVideo.mp4";
mediaRecorder.setOutputFile(dir.getAbsolutePath() + "/" + fileName);
mediaRecorder.setMaxDuration(20000); // Set max duration 60 sec.
mediaRecorder.setOnInfoListener(this);
}
private void prepareMediaRecorder() {
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
// mr.stop();
// mr.release();
recording = false;
mediaRecorder.stop();
Intent intent = new Intent();
setResult(100, intent);
finish();
overridePendingTransition(R.anim.trans_right_in,
R.anim.trans_right_out);
mediaRecorder.release();
moveFile();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
if (!recording) {
File dir = Environment.getExternalStorageDirectory();
File imgFile = new File(dir.getAbsolutePath(), fileName);
if (imgFile.exists()) {
imgFile.delete();
}
camera.stopPreview();
camera.release();
} else {
mediaRecorder.stop();
mediaRecorder.release();
moveFile();
}
recording = false;
Intent intent = new Intent();
setResult(100, intent);
finish();
overridePendingTransition(R.anim.trans_right_in,
R.anim.trans_right_out);
} catch (Exception e) {
// TODO: handle exception
}
}
public void moveFile() {
File temp = Environment.getExternalStorageDirectory();
File from = new File(temp.getAbsolutePath(), fileName);
File dir = Const.getFilePath(Record.this);
File to = new File(dir.getAbsolutePath(), fileName);
from.renameTo(to);
}
#Override
public void onResume() {
super.onResume();
}
}
// xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<SurfaceView
android:id="#+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:background="#55A5D8"
android:padding="5dp"
android:text="REC"
android:textColor="#ffffff"
android:textSize="20sp" />
<TextView
android:id="#+id/txttimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text=""
android:textColor="#55A5D8"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>