How to record 30 sec video automatically ? - android

Here the video automatic record program.but it not working properly. We need automatic 30 sec video record and send it to already set email.
package com.example.videorecord;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.widget.Toast;
public class MainActivity extends Activity implements Callback {
#Override
protected void onDestroy() {
stopRecording();
super.onDestroy();
}
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Camera mCamera;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
mCamera = Camera.open();
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Start");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Start")) {
try {
startRecording();
item.setTitle("Stop");
} catch (Exception e) {
String message = e.getMessage();
Log.i(null, "Problem " + message);
mrec.release();
}
} else if (item.getTitle().equals("Stop")) {
mrec.stop();
mrec.release();
mrec = null;
item.setTitle("Start");
}
return super.onOptionsItemSelected(item);
}
protected void startRecording() throws IOException {
if (mCamera == null)
mCamera = Camera.open();
String filename;
String path;
path = Environment.getExternalStorageDirectory().getAbsolutePath()
.toString();
Date date = new Date();
filename = "/rec" + date.toString().replace(" ", "_").replace(":", "_")
+ ".mp4";
// create empty file it must use
File file = new File(path, filename);
mrec = new MediaRecorder();
mCamera.lock();
mCamera.unlock();
// Please maintain sequence of following code.
// If you change sequence it will not work.
mrec.setCamera(mCamera);
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setOutputFile(path + filename);
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
if (mrec != null) {
mrec.stop();
mrec.release();
mCamera.release();
mCamera.lock();
}
}
private void releaseMediaRecorder() {
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
}
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null) {
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
Log.i("Surface", "Created");
} else {
Toast.makeText(getApplicationContext(), "Camera not available!",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
}

You can use CountDownTimer class.
new CountDownTimer(30000, 1000)
{
public void onTick(long millisUntilFinished)
{}
public void onFinish()
{
// stop Video recording
// call a method which will send video via email.
}
}.start();

you just have to write a method mediaRecorder.setMaxDuration(30000) in your startRecording() method and when mediaRecorder.stop() function'll be called the video'll be saved in destinantion folder you have set for mediarecorder.

Related

Android MediaRecorder preview size changed after start capturing video

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

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;
}
}

Front face camera : sratch on recorded video [Samsung galaxy S3]

Recently, I succeed to open and record a video under Android with my Samsung galaxy S3, however when I try to use the front face camera I just succeed to have a blur we can't see anything but with the default application I can record a video in 720p, so there is someting wrong with my configuration can you see where ?
package com.example.magnificationvideo;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
public class MagnificationVideo extends Activity {
private boolean isRecording = false;
private Camera mCamera;
private SurfaceView mPreview;
private MediaRecorder mMediaRecorder;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private String TAG = "";
private Button captureButton;
public static Camera getCameraInstance(){
Camera c = null;
try {
int nbCameras = Camera.getNumberOfCameras();
System.out.println(nbCameras);
if(nbCameras > 1) {
c = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
} else {
c = Camera.open();
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
return c;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_magnification_video);
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.video_preview);
preview.addView(mPreview);
captureButton = (Button) findViewById(R.id.mybutton);
captureButton.setOnClickListener(recListener);
}
private OnClickListener recListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRecording) {
mMediaRecorder.stop();
releaseMediaRecorder();
mCamera.lock();
captureButton.setText("Capture");
isRecording = false;
} else {
releaseCamera();
if (prepareVideoRecorder()) {
mMediaRecorder.start();
captureButton.setText("Stop");
isRecording = true;
} else {
releaseMediaRecorder();
}
}
}
};
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder();
releaseCamera();
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
mCamera.lock();
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release();
mCamera = null;
}
}
private boolean prepareVideoRecorder(){
mCamera = getCameraInstance();
mCamera.setDisplayOrientation(90);
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.setOrientationHint(90);
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
}
Preview :
package com.example.magnificationvideo;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private String TAG = "";
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setRotation(90);
parameters.set( "cam_mode", 1 );
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (mHolder.getSurface() == null){
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
e.getMessage();
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
Here an example of the result :
Best regards,
Zed13
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));
mrec.setVideoFrameRate(10);
edit the quality and the frame rate , it should be fixed

I can't see preview of camera when starting activity on android

Update:
I could solve the rotation issue (I will write modified code later by an answer). But I can't see preview of camera when starting activity still.
I read below links but didn’t help me.
Can't create Camera preview in onCreate?
[Android camera preview in surfaceview2]
Modify my code if you know any response please.
//-------------------------------------------
I have an android app with below code for capture videos. Every things works correctly except 2 things.
First is : I can't have preview for Camera before capturing. Means I want have a preview by my camera when VideoRecorderActivity1 is started.
Second: when I press start for ToggleButton, then every things rotates 90 degree that is very bad. But output file has correct degree for show. You can use from below code and see result.
Please help and solve my apps issue.Thanks.
Here is my Classess.
import java.io.File;
import java.io.IOException;
import android.hardware.Camera.Parameters;
import android.app.Activity;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class VideoRecorderActivity1 extends Activity
implements SurfaceHolder.Callback
{
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec= new MediaRecorder();
private Camera mCamera;
private ToggleButton mToggleButton=null;
private String Videname="";
private String Videopath="";
private VideoRecorder myVideo=null;
private static Boolean isRecording=false;
String filePath= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator
+"My Audios"+File.separator+"video2camera5.3gpp";
private Boolean ExistVideo(String path1)
{
File file = new File(SDcard.Dir_recordedVideos );
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
if(list[i].getPath().equals(path1))
return true;
}
return false;
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recorder_video);
InitializeUI();
mToggleButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if (((ToggleButton) v).isChecked())
try
{ myVideo=new VideoRecorder();
do{
myVideo.setName();
Videname=myVideo.getName();
myVideo.setPath();
Videopath=myVideo.getPath();
}while(ExistVideo(Videopath));
startRecording();
}
catch (Exception e)
{
String message = e.getMessage();
Log.i(null, "Problem Start"+message);
if(mrec!= null)
mrec.release();
}
else
stopRecording();
}
});
}
protected void startRecording() throws IOException
{
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED))
{
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(this.Videopath).getParentFile();
if (!directory.exists() && !directory.mkdirs())
{
throw new IOException("Path to file could not be created.");
}
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mrec.setOutputFile(Videopath);
mrec.prepare();
isRecording=true;
mrec.start();
}
protected void stopRecording()
{
if(mrec !=null)
mrec.stop();
releaseMediaRecorder();
isRecording=false;
}
private void releaseMediaRecorder()
{
if (mrec != null)
{
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera()
{
if (mCamera != null)
{
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
//------------------------------------------------------------
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
// TODO Auto-generated method stub
}
//------------------------------------------------------------
#Override
public void surfaceCreated(SurfaceHolder holder)
{
if (mCamera != null)
{
Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
}
else
{
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
VideoRecorderActivity1.this.finish();
}
}
//------------------------------------------------------------
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
}
//------------------------------------------------------------
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK )
{
if(isRecording)
mCamera.stopPreview();
mCamera.release();
VideoRecorderActivity1.this.finish();
}
return super.onKeyDown(keyCode, event);
}
//------------------------------------------------------------
private void InitializeUI()
{
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mToggleButton = (ToggleButton) findViewById(R.id.toggleRecordingButton);
}
}
And import this Class:
public class VideoRecorder
{
private String name="";
private static int id=0;
private String path=null;
public VideoRecorder()
{
}
public String getName()
{
return(this.name);
}
public void setName()
{
id++;
this.name="video "+id;
}
public String getPath()
{
return this.path;
}
public void setPath()
{
if (!this.name.contains("."))
{
this.name += ".3gpp";
}
this.path=SDcard.Dir_recordedVideos + this.name;
}
}
You are not creating the preview i think, in your surface created code put this:
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG,"in surfaceCreated"); //Surface created for video preview and playback
try{
mCamera .setPreviewDisplay(holder);
mCamera .startPreview();
}catch(IOException e)
{
Log.v(TAG,"could not start the preview ");
e.printStackTrace();
}
}
In your startrecording function do it like this:
protected void startRecording() throws IOException
{
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED))
{
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(this.Videopath).getParentFile();
if (!directory.exists() && !directory.mkdirs())
{
throw new IOException("Path to file could not be created.");
}
mcamera.stopPreview();
mcamera.unlock();
mrec = new MediaRecorder(); // Works well
mrec.setCamera(mCamera);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mrec.setOutputFile(Videopath);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.prepare();
isRecording=true;
mrec.start();
}

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);
}
}
}

Categories

Resources