Can I use Android Camera in service without preview? - android

I have create a application in Android that using a camera I can measure out the distance between user's face to the phone screen.
Problem description:
Now I want to make it running background so that the feature is available while I am using other applications. It means I should open camera in service without preview, and process it in service.
What I did yet:
I referred some questions here
How to record video from background of application : Android
How to use Android Camera in Background?
Taking picture from camera without preview
API level 16
My Service File
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class RecorderService extends Service {
private static final String TAG = "RecorderService";
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private static Camera mServiceCamera;
private boolean mRecordingStatus;
private MediaRecorder mMediaRecorder;
File path = android.os.Environment.getExternalStorageDirectory();
#Override
public void onCreate() {
Log.i(TAG,"onCreate");
mRecordingStatus = false;
//mServiceCamera = CameraRecorder.mCamera;
mServiceCamera = Camera.open(1);
mSurfaceView = MainActivity.mSurfaceView;
mSurfaceHolder = MainActivity.mSurfaceHolder;
super.onCreate();
if (mRecordingStatus == false)
startRecording();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.i(TAG,"onDestroy");
stopRecording();
mRecordingStatus = false;
super.onDestroy();
}
public boolean startRecording(){
Log.i(TAG,"startRecording");
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
//mServiceCamera = Camera.open();
Camera.Parameters params = mServiceCamera.getParameters();
mServiceCamera.setParameters(params);
Camera.Parameters p = mServiceCamera.getParameters();
final List<Size> listSize = p.getSupportedPreviewSizes();
Size mPreviewSize = listSize.get(2);
Log.v(TAG, "use: width = " + mPreviewSize.width
+ " height = " + mPreviewSize.height);
p.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
p.setPreviewFormat(PixelFormat.YCbCr_420_SP);
mServiceCamera.setParameters(p);
try {
mServiceCamera.setPreviewDisplay(mSurfaceHolder);
mServiceCamera.startPreview();
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
mServiceCamera.unlock();
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(mServiceCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mMediaRecorder.setOutputFile(path+"/outputVideo.mp4");
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mPreviewSize.width, mPreviewSize.height);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();
mRecordingStatus = true;
return true;
} catch (IllegalStateException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
return false;
} catch (IOException e) {
Log.d(TAG, e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Log.i(TAG,"stopRecording");
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
try {
mServiceCamera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
mMediaRecorder.stop();
}catch (Exception ignored)
{
}
mMediaRecorder.reset();
mMediaRecorder.release();
mServiceCamera.stopPreview();
mServiceCamera.release();
mServiceCamera = null;
}
}

You can refer this Question, which discuss how to do video record in the service. The steps to capture image is same as it.
To achieve your requirement, you may need:
Get camera instance in your service. Check this Official Guideline.
Setup your camera parameters. Use the APIs like Camera.getParameters(), Camera.setParameters(), Camera.Parameters.setPictureSize(int with, int height) and Camera.Parameters.setPictureFormat(int format) to do so.
Prepare a file used to store the image. You need to implement Camera.PictureCallback to do so.
Call Camera.startPreview() before you takeing picutre. If you don't call this function before taking picture, you will get exception. (Note: You don't need to do Camera.setPreviewdisplay(SurfaceHolder display) first.)
Call camera.takePicture() in your service. Then you can get the captured image stored on the file you specified.
After it work, don forget to maintain the resource durning lifecycle to acquire/release camera correctly.
Here is my sample code on Github, it is also mentioned in the comment.

Related

Unable to record video and take frames from onPreviewFrame callback at the same time

I am recording video in my Android application using MediaRecorder and I also want frame data through the onPreviewFrame callback.
The issue is: If preview is restarted in surfaceChanged callback then video recording stops working. If it is not restarted, by commenting everything inside surfaceChanged, then video recording keeps working but the onPreviewFrame callback stops working.
How can I make both of them work?
CameraActivity.java
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.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraActivity extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback {
private static final String TAG = "CameraActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Camera mCamera;
private SurfaceView mPreview;
private SurfaceHolder mHolder;
private MediaRecorder mMediaRecorder;
private boolean isRecording = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// Create an instance of Camera
mCamera = getCameraInstance();
if (mCamera != null) {
// Create our Preview view and set it as the content of our activity.
mPreview = (SurfaceView) findViewById(R.id.camera_preview);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mPreview.getHolder();
mHolder.addCallback(this);
}
startLockTask();
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewCallback(this);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
prepareMediaRecorder();
startVideoRecording();
} 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 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
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewCallback(this);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void onPreviewFrame(byte[] bytes, Camera camera) {
}
private boolean prepareMediaRecorder() {
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mediaRecorder, int what, int extra) {
Log.e(TAG, "Media recorder error");
}
});
mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
stopVideoRecording();
releaseMediaRecorder();
prepareMediaRecorder();
startVideoRecording();
}
}
});
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
//mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
// mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mMediaRecorder.setVideoFrameRate(3);
mMediaRecorder.setVideoEncodingBitRate(6000000);
mMediaRecorder.setVideoSize(800, 480);
mMediaRecorder.setMaxDuration(60000);
// Step 4: Set output file
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
// Step 5: Set the preview output
// mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
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;
}
private void startVideoRecording() {
mMediaRecorder.start();
isRecording = true;
}
private void stopVideoRecording() {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
isRecording = false;
}
/** A safe way to get an instance of the Camera object. */
public static 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; // returns null if camera is unavailable
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
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;
}
}
activity_camera.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SurfaceView
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
</LinearLayout>
Your code is almost similar to link provided below but here they used TextureView instead of Surface View and custom CameraView class.
This worked for me, hope helps you too
REF : https://github.com/googlesamples/android-MediaRecorder

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

building camera app on android

hey there I'm new to app developing and I'm trying to build an app which includes the camera.
I followed the android developers guide and yet the app won't run, after trying to look for old answers in this site and not finding any that helped me, I'm asking for your help.
here's my code:
package com.example.camera;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class MainActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
public static String TAG="MainActivity";
private Camera camera;
private CameraPreview preview;
private PictureCallback picture;
private FileNotFoundException err;
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera insta
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
camera = getCameraInstance();
preview = new CameraPreview(this, camera);
FrameLayout FLpreview = (FrameLayout) findViewById(R.id.camera_preview);
FLpreview.addView(preview);
picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: "+ err.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
camera.takePicture(null, null, picture);
}
}
);
}
/** A safe way to get an instance of the Camera object. */
private void releaseCamera(){
if (camera != null){
camera.release(); // release the camera for other applications
camera = null;
}
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
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 {
return null;
}
return mediaFile;
}
}
and here's the code for the surfaceholder:
package com.example.camera;
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 holder;
private Camera camera;
public static String TAG="MainActivity";
public CameraPreview(Context context, Camera cam) {
super(context);
camera=cam;
holder=getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// 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 (holder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(0);
camera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
}
and lastly, Logcat:
07-31 12:06:06.361: W/Camera(998): ICamera died
07-31 12:06:06.361: W/Camera(998): Camera server died!
07-31 12:06:06.381: E/Camera(998): Error 100
Thanks a bunch!
Try to getCameraInstance() a bit later, e.g. onStart()

Video recorded with Android MediaRecorder is corrupted on Samsung Galaxy S2

Good day! I'm learning how to record video with MediaRecorder but recorded video is corrupted when I play it. See this screenshot: http://www.4shared.com/photo/QtmJCHRi/corrupted-video.html. Picture marked with red rectangle in the left upper corner is what camera can see. But it is so small, it's repeating and there is many green areas. Please advise what am I doing wrong. HW is Samsung Galaxy S2 (GT-I9100, Android 2.3.5). I tried to follow this tutorial: http://developer.android.com/guide/topics/media/camera.html#saving-media
Thank you in advance!
CameraRecorderActivity.java
package cz.ryvo.android.camerarecorder;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
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.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
public class CameraRecorderActivity extends Activity
implements SurfaceHolder.Callback, OnClickListener {
private static final String TAG = "CameraRecorderActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Camera mCamera;
private CameraPreview mPreview;
private MediaRecorder mMediaRecorder;
private Button captureButton;
private boolean isRecording = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an instance of Camera.
mCamera = getCameraInstance();
// Create preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
int i = R.id.camera_preview;
Object o = this.findViewById(i);
FrameLayout preview = (FrameLayout) o;
preview.addView(mPreview);
// Add a listener to the Capture button
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
setCaptureButtonText("Capture");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();
// inform the user that recording has started
setCaptureButtonText("Stop");
isRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
}
);
}
public void setCaptureButtonText(String s) {
captureButton.setText(s);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
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;
}
private boolean prepareVideoRecorder(){
//mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setVideoSize(720, 480);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// Step 4: Set output file
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
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;
}
#Override
public void onClick(View v) {
/*
Log.i("onClick", "BEGIN");
if(!recording) {
recording = startRecording();
} else {
stopRecording();
recording = false;
}
Log.i("onClick", "END");
*/
}
#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 (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
private Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
//c = this.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public Camera open() {
int numberOfCameras = Camera.getNumberOfCameras();
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
return Camera.open(i);
}
}
return null;
}
}
CameraPreview.java
package cz.ryvo.android.camerarecorder;
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 static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(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);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
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 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){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
I read about it somewhere (I think it was in SO). The problem is that apparently, the Samsung Galaxy doesn't support recording in HIGH QUALITY (CamcorderProfile.QUALITY_HIGH).
Try with CamcorderProfile.QUALITY_LOW. to see if it works.
EDIT: I found the question with the same issue here

Android Framework Bug Issue

This issue is related with multimedia framework,
I am using Sony Ericsson Xperia X8 (E15i) with Android 2.1.
I face a serious problem related with Video recording. My specific goal is to fetch frames from Video at real time.
While I try to open an application it crashes.
I posted my code here.
Help me for this issue.
MY CODE:::::::::::::::::::::::::
package com.tcs.video;
import java.io.IOException;
import dalvik.system.TemporaryDirectory;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.graphics.*;
//import android.view.Window;
import android.graphics.BitmapFactory.Options;
public class VideoRecorder extends Activity{
//Create objects of MediaRecorder and Preview class
private MediaRecorder recorder;
private Preview mPreview;
boolean flag=false;
boolean startedRecording=false;
boolean stoppedRecording=false;
// In this method, create an object of MediaRecorder class. Create an object of
// RecorderPreview class(Customized View). Add RecorderPreview class object
// as content of UI.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
recorder = new MediaRecorder();
//recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setCamera(Camera.open());
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mPreview = new Preview(VideoRecorder.this,recorder);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(mPreview);
recorder.setPreviewDisplay(mPreview.getSurface());
}
/*!
<p>
Initialize the contents of the Activity's standard options menu. Menu items are to be placed in to menu.
This is called on each press of menu button. In this options to start and stop recording are provided.
Option for start recording has group id 0 and option to stop recording is 1.
(first parameter of menu.add method). Start and stop have different group id, if recording is already
started then it shows stop option else it shows start option.
</p>*/
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
menu.clear();
menu.add(0, 0, 0, "Start Recording");
menu.add(1, 1, 0, "Stop Recording");
menu.setGroupVisible(0, false);
menu.setGroupVisible(1, false);
if(startedRecording==false)
menu.setGroupVisible(0, true);
else if(startedRecording==true&&stoppedRecording==false)
menu.setGroupVisible(1, true);
return true;
}
/*!
<p>
This method receives control when Item in menu option is selected. It contains implementations
to be performed on selection of menu item.
</p>*/
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
/*
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
//start the recorder
recorder.start();
startedRecording=true;
break;
case 1:
//stop the recorder
recorder.stop();
recorder.release();
recorder = null;
stoppedRecording=true;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
class Preview extends SurfaceView implements SurfaceHolder.Callback//,PreviewCallback
{
//Create objects for MediaRecorder and SurfaceHolder.
SurfaceHolder mHolder;
MediaRecorder tempRecorder;
Camera mCamera;
Bitmap currentprev;
//Create constructor of Preview Class. In this, get an object of
//surfaceHolder class by calling getHolder() method. After that add
//callback to the surfaceHolder. The callback will inform when surface is
//created/changed/destroyed. Also set surface not to have its own buffers.
public Preview(Context context,MediaRecorder recorder) {
super(context);
tempRecorder=recorder;
mHolder=getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// TODO Auto-generated constructor stub
Camera.PreviewCallback mPrevCallback = new Camera.PreviewCallback()
{
public void onPreviewFrame( byte[] data, Camera Cam ) {
Log.d("CombineTestActivity", "Preview started");
Log.d("CombineTestActivity", "Data length = " + data.length );
//currentprev.recycle();
/*
currentprev = BitmapFactory.decodeByteArray( data, 0, data.length );
if( currentprev == null )
Log.d("CombineTestActivity", "currentprev is null" );
Log.d("CombineTestActivity", "Preview Finished" );
*/
}
};
mCamera =Camera.open();
Camera.Parameters camParam = mCamera.getParameters();
camParam.setPreviewFormat(PixelFormat.YCbCr_420_SP );
camParam.setPreviewFrameRate(2);
mCamera.setParameters( camParam );
mCamera.setPreviewCallback( mPrevCallback );
}
public Surface getSurface()
{
return mHolder.getSurface();
}
// Implement the methods of SurfaceHolder.Callback interface
// SurfaceCreated : This method gets called when surface is created.
// In this, initialize all parameters of MediaRecorder object.
//The output file will be stored in SD Card.
public void surfaceCreated(SurfaceHolder holder){
//tempRecorder.setOutputFile("/sdcard/recordvideooutput.3gpp");
tempRecorder.setOutputFile("/sdcard/recordvideooutput.mp4");
tempRecorder.setPreviewDisplay(mHolder.getSurface());
try{
//mCamera.release();
//mCamera.unlock();
//mCamera = Camera.open();
//Thread.sleep(1000);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
//Thread.sleep(1000);
//mCamera.unlock();
tempRecorder.setCamera(Camera.open());
//tempRecorder.prepare();
} catch (Exception e) {
String message = e.getMessage().toString();
Log.e("Surface created :Error", message);
tempRecorder.release();
tempRecorder = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
if(tempRecorder!=null)
{
tempRecorder.release();
tempRecorder = null;
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
Log.v("surfaceChanged method", "");
mCamera.startPreview();
}
public void onPreviewFrame(byte [] data, Camera camera)
{
Log.v("onpreviewframe method", "data:"+data.toString());
}
}
}
Seems you forgot this line:
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
or this:
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
And don't forget to add something like this in your manifest:
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.RECORD_AUDIO"
uses-permission android:name="android.permission.RECORD_VIDEO"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Try it and pray ;)
Have you tried with another device ?
I've noticed that MediaRecorder has lot of problem running on xperia x8, so I had this piece of code :
try {
// test availability
MediaRecorder mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorderAvailable = true;
} catch (Exception e) {
Log.d("SOUND_METER", "setAudioSource failed");
recorderAvailable = false;
}
I too would like to know if anyone has actually a real explaination, because lot of my users have this device, so it's very annoying...

Categories

Resources