how to record from front camera - android

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

Related

How to showing current time on Recorded video? (android)

recently when I record button click, start camera preview and digital clock view record
but, when I showing my record video.
not showing digitalclock.
only GLSurfaceView camera preview display.
perhaps, If you've ever added a clock on recorded video,
please advice for me
thanks.
Try this answer ,Thanks to him
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
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;
public class VideoRD extends Activity implements OnClickListener,
SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
public static final String TAG = "VIDEOCAPTURE";
String str_getValue ;
#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);
Intent i1 = getIntent();
str_getValue = i1.getStringExtra("videoImagename");
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.surface);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (recording) {
try {
recorder.stop();
recorder.release();
recording = false;
Log.v(TAG, "Recording Stopped");
initRecorder();
prepareRecorder();
} catch (Exception e) {
// TODO: handle exception
}
} else {
try {
recording = true;
recorder.start();
button.setText("stop");
} catch (Exception e) {
// TODO: handle exception
}
}
}
});
}
private void initRecorder() {
try {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
// recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/audiometer/video/"+str_getValue+"");
recorder.setMaxDuration(1200000000); // 50 seconds
recorder.setMaxFileSize(22000000); // Approximately 5 megabytes
} catch (Exception e) {
// TODO: handle exception
}
}
private void prepareRecorder() {
try {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
}
public void onClick(View v) {
/*
* if (recording) { recorder.stop(); recorder.release(); recording =
* false; Log.v(TAG, "Recording Stopped"); initRecorder();
* prepareRecorder(); } else { recording = true; recorder.start(); }
*/
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
finish();
}
}
dont Forget to add Run time permission for write external storage

Capture video in mp4 format using intent - Android

So I have been searching for the solution from past few days but it seems that I am unable to find any. At first it seems simple enough.
I have an app that uses default Android camera app to capture the video using intent. Video recording is working perfect but the file format is 3gp. I want to record the video in mp4 format but I do not want to implement my own mediarecorder etc to build my own video recording module.
I have also searched for available extra parameters I can pass into the intent for the file format but I couldn't.
Is there any extra parameter that I can use for selecting file format?
Thanks for all your help!
// Use this code to capture Mp4 video.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity{
private static final String TAG = MainActivity.class.getSimpleName();
private Camera myCamera;
private CameraSurfaceView cameraSurfaceView;
private MediaRecorder mediaRecorder;
Button myButton;
boolean recording;
public Context context;
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
final Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recording = false;
setContentView(R.layout.activity_main);
//Get Camera for preview
myCamera = getCameraInstance();
if(myCamera == null){
Log.w(TAG, "camera not found");
Toast.makeText(context,
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
cameraSurfaceView = new CameraSurfaceView(this, myCamera);
FrameLayout cameraPreview = (FrameLayout)findViewById(R.id.videoview);
cameraPreview.addView(cameraSurfaceView);
myButton = (Button)findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
}
Button.OnClickListener myButtonOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(recording){
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
//Exit after saved
//finish();
myButton.setText("REC");
recording = false;
Log.e("file path",fileUri.getPath());
}else{
//Release Camera before MediaRecorder start
releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(context,
"Fail in prepareMediaRecorder()!\n - Ended -",
Toast.LENGTH_LONG).show();
finish();
}
mediaRecorder.start();
recording = true;
myButton.setText("STOP");
Runnable r = new Runnable() {
public void run() {
Timer timer = new Timer();
timer.schedule(doAsynchronousTask, 0, 10000);
}
};
handler.postDelayed(r, 10000);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
};
private Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT); // attempt to get a Camera instance
c.setDisplayOrientation(90);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#SuppressWarnings("unchecked")
public void run() {
try {
if(recording ==true) {
recording = false;
Log.e("file path",fileUri.getPath());
doAsynchronousTask.cancel();
} else{
doAsynchronousTask.cancel();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
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_HIGH));
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
mediaRecorder.setOutputFile(fileUri.getPath());
//mediaRecorder.setOutputFile("/sdcard/myvideo1.mp4");
mediaRecorder.setMaxDuration(10000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M
mediaRecorder.setPreviewDisplay(cameraSurfaceView.getHolder().getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
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 = new MediaRecorder();
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 CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraSurfaceView(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){
// 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){
}
}
#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) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}

preview display in android media recorder

In android how to show preview surface before media recorder start.
my app have video recording functionality,when i navigate to video recording fragment it display black screen,when i start recording using start button camera preview is display and recording start.
how to start preview before recording.
i have added code that i used in onCreateView() of fragment-
surfaceHolder = mySurfaceView.getHolder();
camera = Camera.open();
if(camera!=null){
camera.setDisplayOrientation(90);
Camera.Parameters param;
param = camera.getParameters();
param.setPreviewFrameRate(20);
param.setPreviewSize(176, 144);
camera.setParameters(param);
camera.setPreviewDisplay(surfaceHolder);
}
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
mediaRecorder.setProfile(camcorderProfile_HQ);
String filePath = getOutputMediaFile(MEDIA_TYPE_VIDEO).getPath();
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
mediaRecorder.setOutputFile(filePath);
and the code that i used on start button click-
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
so i am able to recode video by using above code,but not able to show preview before recording start.
Please help me where i am missing.for that black screen is displayed before recoding video.
Thanks in advance.
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null) {
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
try {
//mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
}
If you implement SurfaceHolder.Callback, override the surfaceCreated method like this. This worked for me.
I ran into the same problem. I looked it up and here's my Activity. It took me a bit of effort to make it not crash, so here's the final result. It displays the preview before the user clicks the REC button. (I am also displaying a countdown, but don't mind that). Notice also that there is too much work done on the main thread in this example (when clicking). There are a few things here that aren't best practices, but for a working example I think it's good enough.
import android.app.Activity;
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.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity implements SurfaceHolder.Callback {
private static final String LOG_TAG = MainActivity.class.getCanonicalName();
Button myButton;
MediaRecorder mediaRecorder;
SurfaceHolder surfaceHolder;
boolean recording;
private TextView mTimer;
private Camera mCamera;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recording = false;
mediaRecorder = new MediaRecorder();
mCamera = Camera.open();
initMediaRecorder();
SurfaceView myVideoView = (SurfaceView) findViewById(R.id.videoview);
surfaceHolder = myVideoView.getHolder();
surfaceHolder.addCallback(this);
myButton = (Button) findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
mTimer = (TextView) findViewById(R.id.timer);
}
private Button.OnClickListener myButtonOnClickListener
= new Button.OnClickListener() {
#Override
public void onClick(final View arg0) {
CountDownTimer countDownTimer = new CountDownTimer(90 * 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimer.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
onClick(arg0);
}
};
if (recording) {
// Stop recording and finish
try {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
finish();
} catch (Exception e) {
Log.e(LOG_TAG, "Failed to stop recorder", e);
}
} else {
// Release the camera and start recording
mCamera.release();
countDownTimer.start();
mediaRecorder.start();
recording = true;
myButton.setText("STOP");
}
}
};
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
prepareMediaRecorder();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
private void initMediaRecorder() {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_CIF);
mediaRecorder.setProfile(camcorderProfile_HQ);
File file = new File(getExternalFilesDir(Environment.DIRECTORY_MOVIES), "myvideo.mp4");
if (file.exists()) {
file.delete();
}
mediaRecorder.setOutputFile(file.getAbsolutePath());
mediaRecorder.setMaxDuration(90000); // Set max duration 90 sec.
mediaRecorder.setMaxFileSize(15000000); // Set max file size 15M
}
private void prepareMediaRecorder() {
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException | IOException e) {
Log.e(LOG_TAG, "Failed to prepare recorder", e);
}
}
}

Record video and over the video show time and date over the video

Hi does anybody knows how to record video in android and for example above the recording screen at the bottom show current time and date
Here is code that record video in surface view and store in sdcard and for date and time by This
package com.po;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
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;
public class VideoRD extends Activity implements OnClickListener,
SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
public static final String TAG = "VIDEOCAPTURE";
String str_getValue ;
#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);
Intent i1 = getIntent();
str_getValue = i1.getStringExtra("videoImagename");
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.surface);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (recording) {
try {
recorder.stop();
recorder.release();
recording = false;
Log.v(TAG, "Recording Stopped");
initRecorder();
prepareRecorder();
} catch (Exception e) {
// TODO: handle exception
}
} else {
try {
recording = true;
recorder.start();
button.setText("stop");
} catch (Exception e) {
// TODO: handle exception
}
}
}
});
}
private void initRecorder() {
try {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
// recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/audiometer/video/"+str_getValue+"");
recorder.setMaxDuration(1200000000); // 50 seconds
recorder.setMaxFileSize(22000000); // Approximately 5 megabytes
} catch (Exception e) {
// TODO: handle exception
}
}
private void prepareRecorder() {
try {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
}
public void onClick(View v) {
/*
* if (recording) { recorder.stop(); recorder.release(); recording =
* false; Log.v(TAG, "Recording Stopped"); initRecorder();
* prepareRecorder(); } else { recording = true; recorder.start(); }
*/
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
finish();
}
}

Record Video from Camera via Version Android 2.2

enter code hereWhen I try to recording video from camera at version Android 2.2. It has some errors.No one could find the solution. İs there any bug Android MediaRecorder API. How can I solve this.
I got more errors.You can see some of them in picture.
And an error like that:Camera Preview -13
Thanks a lot.
http://i.stack.imgur.com/72lp7.png
recorder.prepare() fails and throws Java.lang.illegalexeption
Here is Code:
package app.raceway.com;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
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.Toast;
public class VideoCapture extends Activity implements SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
public Camera camera;
File video;
String filePath;
boolean recording = false;
private static final int FRAME_RATE = 15;
private static final int CIF_WIDTH = 320;
private static final int CIF_HEIGHT = 240;
#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);
recorder = new MediaRecorder();
setContentView(R.layout.main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.cameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
String path=Environment.getExternalStorageDirectory().getAbsolutePath()+
"/video/videocapture_example.mpg4";
// make sure the directory we plan to store the recording in exists
File sampleDir = Environment.getExternalStorageDirectory();
try {
video = new File(sampleDir+"/videofile.3gp");
sampleDir.createNewFile();
//video = File.createTempFile("videofile", ".3gp", sampleDir);
}
catch (IOException e)
{
Log.e("deneme","sdcard access error");
}
filePath=video.getAbsolutePath();
}
private void initRecorder() {
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
}
private void prepareRecorder() throws IOException{
recorder.setCamera(camera);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
recorder.setOutputFile(filePath);
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
try {
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onclickSaveVideo(View v) throws IOException {
if (recording) {
Toast t=new Toast(getApplicationContext());
t.makeText(getApplicationContext(), "Video Recording stopped",Toast.LENGTH_SHORT);
t.show();
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
} else {
try {
prepareRecorder();
//recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recording = true;
recorder.prepare();
recorder.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.stop();
Toast t=new Toast(getApplicationContext());
t.makeText(getApplicationContext(), "Video Recording started",Toast.LENGTH_SHORT);
t.show();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera=Camera.open();
try {
camera.setPreviewDisplay(holder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
camera.startPreview();
camera.unlock();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
camera.release();
}
}
Emin,
Based on the image of the logcat output you provide the crash is occuring with the start() method. You will see from the documentation for the start method that prepare() must be called first or else it will throw the IllegalStateException. In your code all the calls the prepare() are commented out?
EDIT: We sorted things out in the comments below my answer. He was running this code on an emulator and MediaRecorder is not supported by the emulator.

Categories

Resources