Front camera in android - android

I am making an application in which user can record video throuh customized camera. and User can also record a video through front camera. It is recorded fine but when we played it in normal Media player it is playing just at 180 degree. I don't know how it can be possible and how to resolve the same? Please suggest me any solution regarding the same.
Code:
package com.irantapps.cameraApplication;
import java.io.File;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaRecorder.VideoEncoder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.irantapps.AfterLoginHome;
import com.irantapps.BaseActivity;
import com.irantapps.CameraPlay_New;
import com.irantapps.R;
import com.irantapps.utility.DateAndLength;
import com.irantapps.utility.VideoDetailsCollection;
/***
* TODO: 1. sound on/off 2. resolution change
*
* #author roman10
*
*/
public class VideoCapture_New extends BaseActivity implements
SurfaceHolder.Callback {
private SurfaceView prSurfaceView;
private ImageButton prStartBtn, prFrontBackCamera;
private Button prSettingsBtn;
private ImageButton btn_Gallery;
public String TAG = "IRANT";
private boolean prRecordInProcess;
private SurfaceHolder prSurfaceHolder;
private Camera prCamera;
private final String cVideoFilePath = "/sdcard/";
Chronometer cm_VideoCapture;
private Context prContext;
public static boolean frontCamera = false;
int mRotation;
LinearLayout linearLayoutRedbtn;
ImageButton btn;
Animation animation;
ImageButton btn_Cancel;
DateAndLength findDateandLength;
private VideoDetailsCollection videoDetails = VideoDetailsCollection.getSingletonObject();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
prContext = this.getApplicationContext();
setContentView(R.layout.videocapture_new);
Utils.createDirIfNotExist(cVideoFilePath);
findDateandLength=DateAndLength.getSingletonObject();
animation = new AlphaAnimation(1, 0); // Change alpha from fully visible
// to invisible
animation.setDuration(500); // duration - half a second
animation.setInterpolator(new LinearInterpolator()); // do not alter
// animation
// rate
animation.setRepeatCount(Animation.INFINITE); // Repeat animation
// infinitely
animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the
// end so the button will
// fade back in
btn = (ImageButton) findViewById(R.id.main_btn1);
btn_Cancel = (ImageButton)findViewById(R.id.btn_wrongTick);
btn_Gallery = (ImageButton)findViewById(R.id.btn_gallerySelector);
linearLayoutRedbtn = (LinearLayout) findViewById(R.id.linear_btn1);
linearLayoutRedbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (prRecordInProcess == false) {
cm_VideoCapture.setBase(SystemClock.elapsedRealtime());
//cm_VideoCapture.clearComposingText();
cm_VideoCapture.start();
try {
startRecording();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
linearLayoutRedbtn.startAnimation(animation);
} else {
stopRecording();
linearLayoutRedbtn.clearAnimation();
cm_VideoCapture.stop();
findDateandLength.setTimeLengthOfVideo(cm_VideoCapture.getText().toString());
//Toast.makeText(getApplicationContext(), "hello..."+cm_VideoCapture.getText(), Toast.LENGTH_LONG).show();
cm_VideoCapture.clearComposingText();
Intent intent = new Intent(VideoCapture_New.this,
CameraPlay_New.class);
startActivity(intent);
}
}
});
btn_Gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video"), 2);
}
});
cm_VideoCapture = (Chronometer) findViewById(R.id.cm_VideoCapture);
prSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
prStartBtn = (ImageButton) findViewById(R.id.main_btn1);
prFrontBackCamera = (ImageButton) findViewById(R.id.btn_frontBackCamera);
//cm_VideoCapture.start();
cm_VideoCapture.clearComposingText();
// prSettingsBtn = (Button) findViewById(R.id.main_btn2);
prRecordInProcess = false;
prStartBtn.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View v) {
if (prRecordInProcess == false) {
cm_VideoCapture.setBase(SystemClock.elapsedRealtime());
//cm_VideoCapture.clearComposingText();
cm_VideoCapture.start();
try {
startRecording();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
stopRecording();
btn.clearAnimation();
cm_VideoCapture.stop();
cm_VideoCapture.clearComposingText();
Intent intent = new Intent(VideoCapture_New.this,
CameraPlay_New.class);
startActivity(intent);
}
}
});
prFrontBackCamera.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// prCamera = openFrontFacingCameraGingerbread();
try {
if (Camera.getNumberOfCameras() == 2) {
if (frontCamera) {
frontCamera = false;
prCamera.stopPreview();
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
} else {
frontCamera = true;
prCamera.stopPreview();
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
}
Intent intent = new Intent(VideoCapture_New.this,
VideoCapture_New.class);
startActivity(intent);
} else {
Toast.makeText(VideoCapture_New.this,
"Your device doesn't contain Front Camera.",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(VideoCapture_New.this,
"Your device is not compatible for Front Camera.",
Toast.LENGTH_SHORT).show();
}
}
});
prSurfaceHolder = prSurfaceView.getHolder();
prSurfaceHolder.addCallback(this);
prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// prCamera.setDisplayOrientation(90);
prMediaRecorder = new MediaRecorder();
btn_Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void surfaceChanged(SurfaceHolder _holder, int _format, int _width,
int _height) {
Camera.Parameters lParam = prCamera.getParameters();
prCamera.setParameters(lParam);
try {
prCamera.setPreviewDisplay(_holder);
prCamera.startPreview();
// prPreviewRunning = true;
} catch (IOException _le) {
_le.printStackTrace();
}
}
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" })
#Override
public void surfaceCreated(SurfaceHolder arg0) {
if (frontCamera == false && prCamera== null) {
/*prCamera = Camera.open();
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}*/
prCamera = Camera.open();
try {
prCamera.setPreviewDisplay(arg0);
// TODO test how much setPreviewCallbackWithBuffer is faster
//prCamera.setPreviewCallback(VideoCapture_New.this);
} catch (IOException e) {
prCamera.release();
prCamera = null;
}
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}
}
/*else if (prCamera == null) {
prCamera = Camera.open();
try {
prCamera.setPreviewDisplay(arg0);
// TODO test how much setPreviewCallbackWithBuffer is faster
//prCamera.setPreviewCallback(VideoCapture_New.this);
} catch (IOException e) {
prCamera.release();
prCamera = null;
}
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}
}*/else if (prCamera!=null){
prCamera.stopPreview();
prCamera.release();
prCamera=null;
}
else if (frontCamera == true) {
try {
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
prCamera = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.i("Camera failed to open: ",
e.getLocalizedMessage());
}
}
}
} catch (Exception e) {
Toast.makeText(VideoCapture_New.this,
"Your Device doesn't compatible for Fron Camera.",
Toast.LENGTH_SHORT).show();
}
}
try {
Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
Camera.getCameraInfo(0, info);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 180;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
this.mRotation = result;
prCamera.setDisplayOrientation(result);
} catch (NoClassDefFoundError e) {
// TODO Auto-generated catch block
e.printStackTrace();
prCamera.setDisplayOrientation(90);
Toast.makeText(VideoCapture_New.this,
"There is no Front Camera Facility.", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (prCamera != null) {
prCamera.stopPreview();
prCamera.setPreviewCallback(null);
prCamera.release();
prCamera = null;
}
}
/*#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
try {
if (prRecordInProcess) {
stopRecording();
} else {
prCamera.stopPreview();
}
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
private MediaRecorder prMediaRecorder;
private final int cMaxRecordDurationInMs = 30000;
private final long cMaxFileSizeInBytes = 5000000;
private final int cFrameRate = 20;
private File prRecordedFile;
private void updateEncodingOptions() {
if (prRecordInProcess) {
stopRecording();
try {
startRecording();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(prContext, "Recording restarted with new options!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(prContext, "Recording options updated!",
Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("NewApi")
private boolean startRecording() throws NoSuchMethodException {
prCamera.stopPreview();
try {
prCamera.unlock();
prMediaRecorder.setCamera(prCamera);
prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
String lVideoFileFullPath = ".mov";
prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
String lDisplayMsg = "Current container format: ";
prMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
prMediaRecorder.setOrientationHint(90);
lDisplayMsg += "Current encoding format: ";
lVideoFileFullPath = Environment.getExternalStorageDirectory() + "/myvideo.mp4";
// prMediaRecorder.setOrientationHint(360);
//prMediaRecorder.setVideoSize(176, 144);
//prMediaRecorder.setVideoFrameRate(12);
prRecordedFile = new File(lVideoFileFullPath);
prMediaRecorder.setOutputFile(prRecordedFile.getPath());
//prMediaRecorder.setVideoFrameRate(cFrameRate);
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
//prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
//prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
// prepare for capturing
// state: DataSourceConfigured => prepared
prMediaRecorder.prepare();
// start recording
// state: prepared => recording
prMediaRecorder.start();
// prStartBtn.setText("Stop");
prRecordInProcess = true;
ExifInterface exif_Video = new ExifInterface(lVideoFileFullPath); //Since API Level 5
String exifOrientation_video = exif_Video.getAttribute(ExifInterface.TAG_ORIENTATION);
return true;
} catch (IOException _le) {
_le.printStackTrace();
return false;
}
}
private void stopRecording() {
prMediaRecorder.stop();
prMediaRecorder.reset();
try {
prCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
// prStartBtn.setText("Start");
prRecordInProcess = false;
prCamera.startPreview();
}
private static final int REQUEST_DECODING_OPTIONS = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_DECODING_OPTIONS:
if (resultCode == RESULT_OK) {
updateEncodingOptions();
}
break;
case 2:
if (resultCode == RESULT_OK) {
//updateEncodingOptions();
if(requestCode == 2)
{
Uri selectedImageUri = intent.getData();
String selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
File file_Video = new File(selectedImagePath);
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(file_Video.getAbsolutePath());
videoDetails.setVideoPath(file_Video.getAbsolutePath());
if(mp.getDuration()<=3)
{
Intent intentGallery = new Intent(VideoCapture_New.this, CameraPlay_New.class);
startActivity(intentGallery);
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder
.setTitle("Info");
// set dialog message
alertDialogBuilder
.setMessage("Video can't be larger than 3 mins.")
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Video Length:"+mp.getDuration());
}
//img.setImageURI(selectedImageUri);
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
/*
* if(collapse==true||collapse_cat==true||collapse_FuelEconomy==true||
* collapse_LatestNews
* ==true||collapse_price==true||collapse_RecentlyViwed==true){
* Intent restartResearchActivity = new
* Intent(ResearchListNew.this,ResearchListNew.class);
* restartResearchActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
* startActivity(restartResearchActivity);
*
* } else { finish(); }
*/
if (prRecordInProcess == false)
{
prCamera.lock();
}
else
{
stopRecording();
prCamera.lock();
}
Intent intent = new Intent(VideoCapture_New.this,
AfterLoginHome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
Thanks in advance.

new Camera().setDisplayOrientation(90);

Related

android video recording with duration limit and low quality

I need to record video for 8 seconds in my app. I am using MediaStore.ACTION_VIDEO_CAPTURE intent for video recording and using these parameters (MediaStore.EXTRA_VIDEO_QUALITY,MediaStore.EXTRA_DURATION_LIMIT) to set quality and duration limit of video recording. but i encountered a very interesting bug i.e. when i set duration limit to 8 seconds and video quality to 1, its working fine and is recording video for 8 seconds but as soon i changes the video quality to 0 and keeping everything same, the video is now recorded for 21 seconds. I am using sony Xperia phone for testing, but when i shift to HTC, duration limit not working in any case neither on setting video quality to 1 nor on setting it to 0.
So i don't know what is happening right now. In severe need. please help. Thanks in advance.
Here is the code I am using..
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File f = null;
try {
f = setUpVideoFile();
filePath = f.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
filePath = null;
}
objectGlobal.setFilepath(filePath);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 8);
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO);
}
I know its bit late to answer this question, but i think i have to, so that if others are facing this problem, they can easily deal with it.
Actually the problem is when you lower the video quality via this
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
the camera intent no longer works as a video recorder. It actually creates a mms when we try lowering the quality. As far as time is concerned, I don't know whether it is a bug in Android or may be some memory constraints. So the solution I adopted is to make custom video recording class using SurfaceView.
So I am pasting the code of Video Recording from one of my projects.Also the video recorded is almost playable in all android/iOS devices, i have tested so far. Here is my Video Recording Class
package com.mukesh.videorecordingsample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class RecordVideoPostsActivity extends Activity implements
SurfaceHolder.Callback, OnClickListener {
protected static final int RESULT_ERROR = 0x00000001;
private static final int MAX_VIDEO_DURATION = 8 * 1000;
private static final int ID_TIME_COUNT = 0x1006;
private SurfaceView mSurfaceView;
private ImageView iv_cancel, iv_ok, iv_record;
private TextView tv_counter;
private SurfaceHolder mSurfaceHolder;
private MediaRecorder mMediaRecorder;
private Camera mCamera;
private List<Size> mSupportVideoSizes;
private String filePath;
private boolean mIsRecording = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_recordvideo);
initView();
}
private void initView() {
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
iv_record = (ImageView) findViewById(R.id.iv_record);
iv_cancel = (ImageView) findViewById(R.id.iv_cancel);
iv_ok = (ImageView) findViewById(R.id.iv_ok);
iv_record.setImageResource(R.drawable.btn_video_start);
tv_counter = (TextView) findViewById(R.id.timer);
tv_counter.setVisibility(View.GONE);
iv_cancel.setOnClickListener(this);
iv_ok.setOnClickListener(this);
iv_record.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
}
private void exit(final int resultCode, final Intent data) {
if (mIsRecording) {
new AlertDialog.Builder(RecordVideoPostsActivity.this)
.setTitle("Video Recorder")
.setMessage("Do you want to exit?")
.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
stopRecord();
if (resultCode == RESULT_CANCELED) {
if (filePath != null)
deleteFile(new File(filePath));
}
setResult(resultCode, data);
finish();
}
})
.setNegativeButton("no",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
return;
}
if (resultCode == RESULT_CANCELED) {
if (filePath != null)
deleteFile(new File(filePath));
}
setResult(resultCode, data);
finish();
}
private void deleteFile(File delFile) {
if (delFile == null) {
return;
}
final File file = new File(delFile.getAbsolutePath());
delFile = null;
new Thread() {
#Override
public void run() {
super.run();
if (file.exists()) {
file.delete();
}
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case ID_TIME_COUNT:
if (mIsRecording) {
if (msg.arg1 > msg.arg2) {
// mTvTimeCount.setVisibility(View.INVISIBLE);
tv_counter.setText("00:00");
stopRecord();
} else {
tv_counter.setText("00:0" + (msg.arg2 - msg.arg1));
Message msg2 = mHandler.obtainMessage(ID_TIME_COUNT,
msg.arg1 + 1, msg.arg2);
mHandler.sendMessageDelayed(msg2, 1000);
}
}
break;
default:
break;
}
}
;
};
private void openCamera() {
try {
this.mCamera = Camera.open();
Camera.Parameters parameters = mCamera.getParameters();
parameters.setRotation(90);
System.out.println(parameters.flatten());
parameters.set("orientation", "portrait");
mCamera.setParameters(parameters);
mCamera.lock();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
try {
mCamera.setDisplayOrientation(90);
} catch (NoSuchMethodError e) {
e.printStackTrace();
}
}
mSupportVideoSizes = parameters.getSupportedVideoSizes();
if (mSupportVideoSizes == null || mSupportVideoSizes.isEmpty()) {
String videoSize = parameters.get("video-size");
Log.i(EmBazaarConstants.APP_NAME, videoSize);
mSupportVideoSizes = new ArrayList<Camera.Size>();
if (!RecordVideoPostsActivity.isEmpty(videoSize)) {
String[] size = videoSize.split("x");
if (size.length > 1) {
try {
int width = Integer.parseInt(size[0]);
int height = Integer.parseInt(size[1]);
mSupportVideoSizes.add(mCamera.new Size(width,
height));
} catch (Exception e) {
Log.e(EmBazaarConstants.APP_NAME, e.toString());
}
}
}
}
for (Size size : mSupportVideoSizes) {
Log.i(EmBazaarConstants.APP_NAME, size.width + "<>" + size.height);
}
} catch (Exception e) {
Log.e(EmBazaarConstants.APP_NAME, "Open Camera error\n" + e.toString());
}
}
private boolean initVideoRecorder() {
if (mCamera == null) {
mCamera = Camera.open();
mCamera.unlock();
} else {
mCamera.unlock();
}
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setCamera(mCamera);
try {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
try {
CamcorderProfile lowProfile = CamcorderProfile
.get(CamcorderProfile.QUALITY_LOW);
CamcorderProfile hightProfile = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
if (lowProfile != null && hightProfile != null) {
lowProfile.audioCodec = MediaRecorder.AudioEncoder.AAC;
lowProfile.duration = hightProfile.duration;
lowProfile.videoCodec = MediaRecorder.VideoEncoder.H264;
lowProfile.videoFrameRate = hightProfile.videoFrameRate;
lowProfile.videoBitRate = 1500000 > hightProfile.videoBitRate ? hightProfile.videoBitRate
: 1500000;
if (mSupportVideoSizes != null && !mSupportVideoSizes.isEmpty()) {
int width = 640;
int height = 480;
Collections.sort(mSupportVideoSizes, new SizeComparator());
int lwd = mSupportVideoSizes.get(0).width;
for (Size size : mSupportVideoSizes) {
int wd = Math.abs(size.width - 640);
if (wd < lwd) {
width = size.width;
height = size.height;
lwd = wd;
} else {
break;
}
}
lowProfile.videoFrameWidth = width;
lowProfile.videoFrameHeight = height;
}
mMediaRecorder.setProfile(lowProfile);
}
} catch (Exception e) {
try {
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
} catch (Exception ex) {
ex.printStackTrace();
}
if (mSupportVideoSizes != null && !mSupportVideoSizes.isEmpty()) {
Collections.sort(mSupportVideoSizes, new SizeComparator());
Size size = mSupportVideoSizes.get(0);
try {
mMediaRecorder.setVideoSize(size.width, size.height);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
try {
mMediaRecorder.setVideoSize(640, 480);
} catch (Exception ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
}
File f = null;
try {
f = setUpVideoFile();
filePath = f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
f = null;
filePath = null;
}
mMediaRecorder.setOutputFile(filePath);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
try {
mMediaRecorder.setOrientationHint(90);
} catch (NoSuchMethodError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d("VideoPreview",
"IllegalStateException preparing MediaRecorder: "
+ e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d("VideoPreview",
"IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (Exception e) {
releaseMediaRecorder();
e.printStackTrace();
}
return true;
}
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 void startRecord() {
try {
if (initVideoRecorder()) {
mMediaRecorder.start();
iv_record.setImageResource(R.drawable.btn_video_stop);
} else {
releaseMediaRecorder();
iv_record.setImageResource(R.drawable.btn_video_start);
}
tv_counter.setVisibility(View.VISIBLE);
tv_counter.setText("00:0" + (MAX_VIDEO_DURATION / 1000));
Message msg = mHandler.obtainMessage(ID_TIME_COUNT, 1,
MAX_VIDEO_DURATION / 1000);
mHandler.sendMessage(msg);
mIsRecording = true;
} catch (Exception e) {
showShortToast("problem while capturing video");
e.printStackTrace();
exit(RESULT_ERROR, null);
}
}
private void stopRecord() {
try {
mMediaRecorder.stop();
} catch (Exception e) {
if (new File(filePath) != null
&& new File(filePath).exists()) {
new File(filePath).delete();
}
}
releaseMediaRecorder();
mCamera.lock();
iv_record.setImageResource(R.drawable.btn_video_start);
mIsRecording = false;
iv_record.setVisibility(View.GONE);
iv_cancel.setVisibility(View.VISIBLE);
iv_ok.setVisibility(View.VISIBLE);
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, Camera camera) {
Camera.CameraInfo info = new Camera.CameraInfo(); // Since API level 9
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
} else {
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
#Override
protected void onResume() {
super.onResume();
openCamera();
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (Exception e) {
}
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
try {
mCamera.stopPreview();
} catch (Exception e) {
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit(RESULT_CANCELED, null);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.iv_ok:
Intent data = new Intent();
if (filePath != null) {
data.putExtra("videopath", filePath);
}
exit(RESULT_OK, data);
break;
case R.id.iv_cancel:
exit(RESULT_CANCELED, null);
break;
case R.id.iv_record:
if (mIsRecording) {
stopRecord();
} else {
startRecord();
}
break;
default:
break;
}
}
protected void showShortToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private File setUpVideoFile() throws IOException {
File videoFile = null;
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
File storageDir = new File(
EmBazaarConstants.LOCAL_STORAGE_BASE_PATH_FOR_POSTED_VIDEOS)
.getParentFile();
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
videoFile = File.createTempFile(EmBazaarConstants.MP4_FILE_PREFIX
+ System.currentTimeMillis() + "_",
EmBazaarConstants.MP4_FILE_SUFIX, storageDir);
} else {
Log.v(getString(R.string.app_name),
"External storage is not mounted READ/WRITE.");
}
return videoFile;
}
private class SizeComparator implements Comparator<Size> {
#Override
public int compare(Size lhs, Size rhs) {
return rhs.width - lhs.width;
}
}
public static boolean isEmpty(String str) {
return str == null || "".equals(str.trim());
}
}
and you can simply call this class in your Activity like this
if (isDeviceSupportCamera()) {
startActivityForResult(new Intent(PostStatusActivity.this,
yourActivity.class),
EmBazaarConstants.CAMERA_CAPTURE_VIDEO);
} else {
Toast.makeText(this, "Your device doesn't support camera",
Toast.LENGTH_LONG).show();
}
and here is isDeviceSupportCamera() function
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
In your onActivityResult, you have to write this code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EmBazaarConstants.CAMERA_CAPTURE_VIDEO
&& resultCode == RESULT_OK) {
if (data != null && data.getStringExtra("videopath") != null)
videoFilePath= data.getStringExtra("videopath");
}
}
Hope this helps.
** Although we have new Camera2 APIs in android lollipop, but this code still works in android lollipop as well.But still you can change to new Camera2 APIs,if you want.

Open video file from File Explorer and playing in my videoplayer activity

I have my VideoPlayerActivity.java and I want to open when I press on a video file from my sdcard through my file explore or another application
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.webkit.URLUtil;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.TextView;
import android.widget.Toast;
public class VideoPlayerActivity extends Activity implements OnErrorListener, OnBufferingUpdateListener,
OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener,
MediaPlayerControl, SurfaceHolder.Callback, VideoControllerView.MediaPlayerControl, Runnable {
private static final String TAG = "Player";
MediaPlayer mediaPlayer;
SurfaceHolder surfaceHolder;
SurfaceView playerSurfaceView;
VideoControllerView controller;
private int position;
private String videoPath;
int videoWidth, videoHeight;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video_player);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
videoPath = getIntent().getStringExtra("videoPath");
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
controller = new VideoControllerView(this);
try {
// String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
/* final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path.equals(current) && mediaPlayer != null) {
mediaPlayer.start();
return;
}
current = path;*/
// Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 166);
// Uri uri = MediaStore.Files.getContentUri("external");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mediaPlayer.prepareAsync();
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
Intent intent = new Intent();
intent.setClass(VideoPlayerActivity.this, MainActivity.class);
startActivity(intent);
}
});
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(videoPath);
mediaPlayer.prepare();
Log.v(TAG, "Duration: ===>" + mediaPlayer.getDuration());
mediaPlayer.start();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
} /*catch (Exception e) {
Log.e(TAG, "error: "+ e.getMessage(), e);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}*/
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(path);
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
private final Handler handler = new Handler (){
#Override
public void handleMessage(Message msg) {
final int currentPos = msg.getData().getInt("CurrentPosition");
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
/*if(controller.isShowing()) {
controller.hide();
}else {
controller.show();
}*/
return false;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
mediaPlayer.start();
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
#Override
public void toggleFullScreen() {
}
// End VideoMediaController.MediaPlayerControl
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
videoWidth = width;
videoHeight = height;
Toast.makeText(getApplicationContext(),
String.valueOf(videoWidth) + "x" + String.valueOf(videoHeight),
Toast.LENGTH_SHORT).show();
if (mediaPlayer.isPlaying()){
surfaceHolder.setFixedSize(videoWidth, videoHeight);
}
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void run() {
// TODO Auto-generated method stub
controller = new VideoControllerView(this);
try {
mediaPlayer.setDataSource(videoSrc);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
/*
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putInt("CurrentPosition", mediaPlayer.getCurrentPosition());
msg.setData(bundle);
handler.sendMessage(msg);
// handler.postDelayed(callBack, 500);*/
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
}
And my logcat error is
01-03 20:42:14.881: V/MediaPlayer(14737): setVideoSurfaceTexture
01-03 20:42:14.881: W/System.err(14737): java.lang.NullPointerException: uriString
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:468)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri$StringUri.<init>(Uri.java:458)
01-03 20:42:14.901: W/System.err(14737): at android.net.Uri.parse(Uri.java:430)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1256)
01-03 20:42:14.901: W/System.err(14737): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1221)
My XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:keepScreenOn="true"
android:id="#+id/video_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SurfaceView
android:id="#+id/playersurface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
</LinearLayout>
And one more question. I have this public void method for streaming
private void setDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
mediaPlayer.setDataSource(path);
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[2000];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
mediaPlayer.setDataSource(tempPath);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
How can I used to stream files from another application program?
When I play video from main activity it plays and when I quit and go to file explorer and chose my player from custom dialog box and open I have that problem with uriString...
When navigating through your files you can set a clicklistener on a thumbnail. I use this code to fire up a full-screen video editor:
thumbNail.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (pathType.equals("image")) {
<snip>
}
else {
// music file
}
else {
// must be video
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(cmsURL + pathListFull,"video/mp4");
PackageManager packageManager = getActivity().getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivity(intent);
}
else {
Log.d("SHOWFILE", "no intents available");
}
}
}
});

video recorder in MIUI OS throw android.media.MediaRecorder.setOutputFormat(Native Method)

i use surfaceview to record video, work well in HTC and SAMSUNG device, but on MIUI device not work, and throw exception as bellow:
04-28 11:45:12.869: E/MediaRecorder(28941): setOutputFormat called in an invalid state: 4
04-28 11:45:12.869: W/System.err(28941): java.lang.IllegalStateException
04-28 11:45:12.869: W/System.err(28941): at android.media.MediaRecorder.setOutputFormat(Native Method)
04-28 11:45:12.869: W/System.err(28941): at com.dream.gushihui.TakeVideoActivity.onClick(TakeVideoActivity.java:416)
04-28 11:45:12.869: W/System.err(28941): at android.view.View.performClick(View.java:2486)
04-28 11:45:12.869: W/System.err(28941): at android.view.View$PerformClick.run(View.java:9130)
04-28 11:45:12.869: W/System.err(28941): at android.os.Handler.handleCallback(Handler.java:587)
04-28 11:45:12.869: W/System.err(28941): at android.os.Handler.dispatchMessage(Handler.java:92)
04-28 11:45:12.869: W/System.err(28941): at android.os.Looper.loop(Looper.java:130)
04-28 11:45:12.869: W/System.err(28941): at android.app.ActivityThread.main(ActivityThread.java:3703)
04-28 11:45:12.869: W/System.err(28941): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 11:45:12.869: W/System.err(28941): at java.lang.reflect.Method.invoke(Method.java:507)
04-28 11:45:12.869: W/System.err(28941): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
04-28 11:45:12.869: W/System.err(28941): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
04-28 11:45:12.869: W/System.err(28941): at dalvik.system.NativeStart.main(Native Method)
enter code here
public class TakeVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback {
private static final int REQUEST_CODE_GET_LOCAL_VIDEO = 11;
//默认录制视频的时长-3分钟
private static final int DEFAULT_RECORD_TIME = 180;
private TextView mTextViewControlLight, mTextViewControlCamera, mTextViewBack,
mTextViewChooseLocalVideo, mTextViewControlVideo, mTextViewRecordPrompt;
private SurfaceView surfaceview;// 显示视频的控件
// 用来显示视频的一个接口,我靠不用还不行,也就是说用mediarecorder录制视频还得给个界面看
// 想偷偷录视频的同学可以考虑别的办法。。嗯需要实现这个接口的Callback接口
private SurfaceHolder surfaceHolder;
//获取屏幕的宽和高,用于设置视频的尺寸大小
private int screenWidth, screenHight;
private MediaRecorder mediarecorder;// 录制视频的类
private boolean isRecording = false;
public static String VIDEO_RECORD_PATH = Environment.getExternalStorageDirectory().toString()+"/12fou/videoRecord/";
// public static String VIDEO_TEMP_NAME = "video_tmp.mp4";
private String videoName;
private AlertDialog dialog;
private Camera camera;
//闪光灯是否开启
private boolean isFlashLight = false;
//当前的camera是否是前置摄像头
private boolean isFacingCamera = false;
private TextView mTextViewRecordTime;
private Timer timer = new Timer();
//视频剩余的时间
private int recordRemainTime = 0;
private boolean isSuccess = false;
private String message = "";
private ProgressDialog mProgressDialog;
private final static int UPLOAD_VIDEO_END = 1;
private static final int SHOW_PROGRESS_DIALOG = 2;
private static final int DISMISS_PROGRESS_DIALOG = 3;
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_PROGRESS_DIALOG:
try {
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mProgressDialog = null;
}
mProgressDialog = new ProgressDialog(TakeVideoActivity.this);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage((String) msg.obj);
mProgressDialog.show();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
case DISMISS_PROGRESS_DIALOG:
try {
if ((mProgressDialog != null)
&& mProgressDialog.isShowing())
mProgressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
case UPLOAD_VIDEO_END:
try {
if(isSuccess){
Utils.showToast(TakeVideoActivity.this, "上传视频成功");
}else{
Utils.showToast(TakeVideoActivity.this, message);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
default:
break;
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 选择支持半透明模式,在有surfaceview的activity中使用。
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.take_video_activity);
initViews();
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
screenWidth = displayMetrics.widthPixels;
screenHight = displayMetrics.heightPixels;
System.out.println("****screen width="+screenWidth+",screen hight="+screenHight);
// initValues();
}
private void initViews(){
mTextViewControlLight = (TextView) findViewById(R.id.textview_control_light);
mTextViewControlCamera = (TextView) findViewById(R.id.textview_control_camera);
mTextViewBack = (TextView) findViewById(R.id.textview_back);
mTextViewChooseLocalVideo = (TextView) findViewById(R.id.textview_choose_local_video);
mTextViewControlVideo = (TextView) findViewById(R.id.textview_video_control);
mTextViewRecordPrompt = (TextView) findViewById(R.id.textview_record_prompt);
mTextViewRecordTime = (TextView) findViewById(R.id.textview_record_time);
surfaceview = (SurfaceView) this.findViewById(R.id.surfaceview);
SurfaceHolder holder = surfaceview.getHolder();// 取得holder
holder.addCallback(this); // holder加入回调接口
// setType必须设置,要不出错.
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setKeepScreenOn(true);
mTextViewControlLight.setOnClickListener(this);
mTextViewControlCamera.setOnClickListener(this);
mTextViewBack.setOnClickListener(this);
mTextViewChooseLocalVideo.setOnClickListener(this);
mTextViewControlVideo.setOnClickListener(this);
}
private void initValues(){
try {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
if(camera != null){
Camera.Parameters parameters = camera.getParameters();
parameters.setRotation(90);
if(isFlashLight)
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
else
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);//摄像图旋转90度
camera.unlock();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
// 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder
surfaceHolder = holder;
/*try {
camera = Camera.open();
if(camera != null){
Camera.Parameters parameters = camera.getParameters();
parameters.setRotation(90);
if(isFlashLight)
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
else
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);//摄像图旋转90度
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}*/
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder
surfaceHolder = holder;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
surfaceview = null;
surfaceHolder = null;
mediarecorder = null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent;
switch (v.getId()) {
case R.id.textview_back: //返回
try {
if (mediarecorder != null) {
// 停止录制
mediarecorder.stop();
// 释放资源
mediarecorder.release();
mediarecorder = null;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finish();
break;
case R.id.textview_control_light: //控制是否开启闪光灯
if (isFlashLight) {
turnOffFlashLight();
} else {
turnOnFlashLight();
}
break;
case R.id.textview_control_camera: //控制是前置还是后置摄像头
controlCamera();
break;
case R.id.textview_record_prompt: //摄像机如何放置的提示信息
break;
case R.id.textview_choose_local_video: //选择本地视频
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("video/*");
startActivityForResult(intent, REQUEST_CODE_GET_LOCAL_VIDEO);
break;
case R.id.textview_video_control: //控制是拍摄还是暂停录视频
if(isRecording){//现在在录制,暂停录制
try {
if (mediarecorder != null) {
// 停止录制
mediarecorder.stop();
// 释放资源
mediarecorder.release();
mediarecorder = null;
File file4 = new File(VIDEO_RECORD_PATH+videoName);
// File file4 = new File(Environment.getExternalStorageDirectory().toString()+"/delete_red_bg.png");
if(file4.exists()){
/*AlertDialog.Builder builder = new AlertDialog.Builder(TakeVideoActivity.this);
builder.setTitle("属性");
builder.setItems(R.array.take_video_menu_option, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case 0: //预览
break;
case 1: //上传
final Intent intent = new Intent();
intent.setClass(TakeVideoActivity.this, UploadVideoActivity.class);
intent.putExtra(UploadVideoActivity.INTENT_KEY_FILE_PATH, VIDEO_RECORD_PATH+videoName);
startActivity(intent);
break;
case 2: //放弃
break;
default:
break;
}
}
});
dialog = builder.create();
dialog.setCancelable(false);
dialog.show();*/
intent = new Intent();
intent.setClass(TakeVideoActivity.this, UploadVideoActivity.class);
intent.putExtra(UploadVideoActivity.INTENT_KEY_FILE_PATH, VIDEO_RECORD_PATH+videoName);
startActivity(intent);
}
}
mTextViewControlVideo.setBackgroundResource(R.drawable.tabbar_camera_recording);
showViewWhenRecordEnd();
isRecording = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}else{//未录视频,开始录视频
mTextViewRecordPrompt.setVisibility(View.GONE);
videoName = getDateString()+".mp4";
mediarecorder = new MediaRecorder();// 创建mediarecorder对象
mediarecorder.setOrientationHint(90);////视频旋转90度
try {
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if(isFacingCamera)
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
else
camera = Camera.open();
if(camera != null){
Camera.Parameters parameters = camera.getParameters();
parameters.setRotation(90);
if(isFlashLight)
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
else
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);//摄像图旋转90度
camera.unlock();
mediarecorder.setCamera(camera);
}
/*recordVideo();
isRecording = true;*/
/*if(camera != null){
camera.unlock();
mediarecorder.setCamera(camera);
}*/
// 设置录制视频源为Camera(相机)
mediarecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediarecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
mediarecorder.setProfile(cpHigh);
// 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediarecorder.setMaxDuration(180000); //Set max duration 300 sec
mediarecorder.setMaxFileSize(20000000); // Set max file size 20M
// 设置录制的视频编码h263 h264
mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
// 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
// mediarecorder.setVideoSize(176, 144);
// 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
// mediarecorder.setVideoFrameRate(24);
mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
// 设置视频文件输出的路径
File file = new File(VIDEO_RECORD_PATH+videoName);
if(!file.exists())
file.mkdirs();
file.delete();
mediarecorder.setOutputFile(VIDEO_RECORD_PATH+videoName);
try {
// 准备录制
mediarecorder.prepare();
// 开始录制
mediarecorder.start();
isRecording = true;
mTextViewControlVideo.setBackgroundResource(R.drawable.tabbar_camera_stop);
hideViewWhenRecording();
recordRemainTime = DEFAULT_RECORD_TIME;
timer.schedule(task, 1000, 1000);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
default:
break;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void recordVideo(){
try {
mediarecorder = new MediaRecorder();// 创建mediarecorder对象
// 设置录制视频源为Camera(相机)
mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// 设置录制的视频编码h263 h264
mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
// 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
mediarecorder.setVideoSize(176, 144);
// 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
mediarecorder.setVideoFrameRate(20);
mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
// 设置视频文件输出的路径
mediarecorder.setOutputFile(VIDEO_RECORD_PATH+videoName);
try {
// 准备录制
mediarecorder.prepare();
// 开始录制
mediarecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 将当前的时间转换成为年月日时分秒毫秒 的格式
* #return
*/
private String getDateString(){
Date current = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String s = sdf.format(current);
return s;
}
/**
* 调整camera是指不会选择90度
* #param activity
* #param cameraId
* #param camera
*/
public static void setCameraDisplayOrientation ( Activity activity ,
int cameraId , android.hardware.Camera camera ) {
try {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo( cameraId , info);
int rotation = activity.getWindowManager ().getDefaultDisplay ().getRotation ();
int degrees = 0 ;
switch ( rotation ) {
case Surface.ROTATION_0 : degrees = 0 ; break ;
case Surface.ROTATION_90 : degrees = 90 ; break ;
case Surface.ROTATION_180 : degrees = 180 ; break ;
case Surface.ROTATION_270 : degrees = 270 ; break ;
}
int result ;
if ( info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
result = ( info.orientation + degrees ) % 360 ;
result = ( 360 - result ) % 360 ; // compensate the mirror
} else { // back-facing
result = ( info.orientation - degrees + 360 ) % 360 ;
}
camera.setDisplayOrientation( result );
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 设置开启或者关闭闪光灯
* #param isEnable
*/
private void setFlashlightEnabled(boolean isEnable) {
try {
Method method = Class.forName("android.os.ServiceManager")
.getMethod("getService", String.class);
IBinder binder = (IBinder) method.invoke(null,new Object[] { "hardware" });
IHardwareService localhardwareservice = IHardwareService.Stub
.asInterface(binder);
localhardwareservice.setFlashlightEnabled(isEnable);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 打开闪光灯
*/
private void turnOnFlashLight(){
try {
if(camera == null)
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
Camera.Parameters mParameters;
mParameters = camera.getParameters();
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(mParameters);
isFlashLight = true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 关闭闪光灯
*/
private void turnOffFlashLight(){
try {
Camera.Parameters mParameters;
camera.reconnect();
mParameters = camera.getParameters();
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(mParameters);
// camera.release();
isFlashLight = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
}
/**
* 控制前置或后置摄像头的切换
* http://www.cnblogs.com/stay/archive/2011/06/24/2089129.html
*/
private void controlCamera(){
try {
try {
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD){
//2.3以上的手机
Utils.logDebug("*****camera number="+Camera.getNumberOfCameras());
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
Utils.logDebug("*****camera info="+info.facing);
if (!isFacingCamera && info.facing == CameraInfo.CAMERA_FACING_FRONT) {// 这就是前置摄像头,亲。
camera = Camera.open(i);
isFacingCamera = true;
break;
}else if(isFacingCamera && info.facing == CameraInfo.CAMERA_FACING_BACK){
// camera = Camera.open(i);
camera = Camera.open();
isFacingCamera = false;
break;
}
}
}else{
//2.3及其以下的版本
}
if (camera == null) {
camera = Camera.open();
}
try {
if(camera != null){
Camera.Parameters parameters = camera.getParameters();
parameters.setRotation(90);
if(isFlashLight)
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
else
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);//摄像图旋转90度
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 上传视频线程
* #author Xiang Yong
*
*/
private class UploadVideoThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
Message msg = new Message();
msg.what = SHOW_PROGRESS_DIALOG;
msg.obj = "视频上传中...";
myHandler.sendMessage(msg);
isSuccess = false;
String videoUrl = "";
try {
String result = UploadFileThread.uploadFile("http://api.12fou.net/api.php/user/upvideo", VIDEO_RECORD_PATH+videoName, null);
if(result != null && !"".equals(result)){
JSONObject jsonObject = new JSONObject(result);
String statu = jsonObject.getString("result");
if("true".equalsIgnoreCase(statu)){
videoUrl = jsonObject.getString("video");
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
myHandler.sendEmptyMessage(UPLOAD_VIDEO_END);
myHandler.sendEmptyMessage(DISMISS_PROGRESS_DIALOG);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
try {
if(resultCode == RESULT_OK){
switch (requestCode) {
case REQUEST_CODE_GET_LOCAL_VIDEO: //获取本地视频
Uri uri = data.getData();
String path = getPath(uri);
Utils.logDebug("***on activity result data="+data.getData()+",path="+path);
if(path != null && !"".equals(path)){
Intent intent = new Intent();
intent.setClass(TakeVideoActivity.this, UploadVideoActivity.class);
intent.putExtra(UploadVideoActivity.INTENT_KEY_FILE_PATH, path);
startActivity(intent);
}else{
Utils.showToast(TakeVideoActivity.this, "文件不存在");
}
break;
default:
break;
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public String getPath(Uri uri) {
try {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
startManagingCursor(cursor);
int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "";
}
TimerTask task = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
runOnUiThread(new Runnable() {
public void run() {
recordRemainTime--;
mTextViewRecordTime.setText(Utils.formatSecondToMMSS(recordRemainTime));
if(recordRemainTime < 0){
timer.cancel();
mTextViewControlVideo.performClick();
}
}
});
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
};
private void hideViewWhenRecording(){
try {
mTextViewChooseLocalVideo.setVisibility(View.INVISIBLE);
mTextViewControlLight.setVisibility(View.GONE);
mTextViewControlCamera.setVisibility(View.GONE);
mTextViewRecordTime.setVisibility(View.VISIBLE);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void showViewWhenRecordEnd(){
try {
mTextViewChooseLocalVideo.setVisibility(View.VISIBLE);
mTextViewControlLight.setVisibility(View.VISIBLE);
mTextViewControlCamera.setVisibility(View.VISIBLE);
mTextViewRecordTime.setVisibility(View.GONE);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
You call mediarecorder.setOutputFormat() after you have called mediarecorder.setProfile().
setProfile() also sets the outputFormat. This seems to cause your problem.
So: Either use setProfile(). Or set all the paramters (OutputFormat, Size etc.) yourself.

Camera automatically tilt when we start Recording

I am facing an issue in my app as when I start recording through camera it tilts to landscape which is not the requirement. The requirement is Recording should start according the the orientation of the Device. Means if device is in portrait mode then recording should start in Portrait and If camera in landscape mode then recording will atart in landscape.
But in our case when we click on start recording button then camera orientation will automaticaly changed to Landscape but Device still with the portrait orientation.
So, Please suggest any solution regarding that.
Code:
package com.irant.cameraApplication;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.media.MediaRecorder.VideoEncoder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.Toast;
import com.irant.a1techno.CameraPlay;
import com.irant.a1techno.R;
/***
* TODO: 1. sound on/off
* 2. resolution change
* #author roman10
*
*/
public class VideoCapture_New extends Activity implements SurfaceHolder.Callback {
private SurfaceView prSurfaceView;
private ImageButton prStartBtn, prFrontBackCamera;
private Button prSettingsBtn;
public String TAG = "IRANT";
private boolean prRecordInProcess;
private SurfaceHolder prSurfaceHolder;
private Camera prCamera;
private final String cVideoFilePath = "/sdcard/";
Chronometer cm_VideoCapture;
private Context prContext;
public static boolean frontCamera= false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
prContext = this.getApplicationContext();
setContentView(R.layout.videocapture_new);
Utils.createDirIfNotExist(cVideoFilePath);
cm_VideoCapture = (Chronometer)findViewById(R.id.cm_VideoCapture);
prSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
prStartBtn = (ImageButton) findViewById(R.id.main_btn1);
prFrontBackCamera = (ImageButton)findViewById(R.id.btn_frontBackCamera);
// prSettingsBtn = (Button) findViewById(R.id.main_btn2);
prRecordInProcess = false;
prStartBtn.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
if (prRecordInProcess == false) {
startRecording();
cm_VideoCapture.start();
} else {
stopRecording();
cm_VideoCapture.stop();
Intent intent = new Intent(VideoCapture_New.this, CameraPlay.class);
startActivity(intent);
}
}
});
prFrontBackCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//prCamera = openFrontFacingCameraGingerbread();
try{
if(prCamera.getNumberOfCameras()==2)
{
if(frontCamera)
{
frontCamera = false;
prCamera.stopPreview();
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
}
else
{
frontCamera = true;
prCamera.stopPreview();
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
}
Intent intent = new Intent(VideoCapture_New.this, VideoCapture_New.class);
startActivity(intent);
}
else
{
Toast.makeText(VideoCapture_New.this, "Your device doesn't contain Front Camera.", Toast.LENGTH_SHORT).show();
}
}catch(Exception e)
{
e.printStackTrace();
Toast.makeText(VideoCapture_New.this, "Your device is not compatible for Front Camera.", Toast.LENGTH_SHORT).show();
}
}
});
prSurfaceHolder = prSurfaceView.getHolder();
prSurfaceHolder.addCallback(this);
prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
prMediaRecorder = new MediaRecorder();
}
private Camera openFrontFacingCameraGingerbread()
{
Camera camera = null;
// Look for front-facing camera, using the Gingerbread API.
// Java reflection is used for backwards compatibility with pre-Gingerbread APIs.
try {
Class<?> cameraClass = Class.forName("android.hardware.Camera");
Object cameraInfo = null;
Field field = null;
int cameraCount = 0;
Method getNumberOfCamerasMethod = cameraClass.getMethod( "getNumberOfCameras" );
if ( getNumberOfCamerasMethod != null ) {
cameraCount = (Integer) getNumberOfCamerasMethod.invoke( null, (Object[]) null );
}
Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo");
if ( cameraInfoClass != null ) {
cameraInfo = cameraInfoClass.newInstance();
}
if ( cameraInfo != null ) {
field = cameraInfo.getClass().getField( "facing" );
}
Method getCameraInfoMethod = cameraClass.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass );
if ( getCameraInfoMethod != null && cameraInfoClass != null && field != null ) {
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
getCameraInfoMethod.invoke( null, camIdx, cameraInfo );
int facing = field.getInt( cameraInfo );
if ( facing == 1 ) { // Camera.CameraInfo.CAMERA_FACING_FRONT
try {
Method cameraOpenMethod = cameraClass.getMethod( "open", Integer.TYPE );
if ( cameraOpenMethod != null ) {
camera = (Camera) cameraOpenMethod.invoke( null, camIdx );
}
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
camera= prCamera;
}
}
}
}
}
// Ignore the bevy of checked exceptions the Java Reflection API throws - if it fails, who cares.
catch ( ClassNotFoundException e ) {Log.e(TAG, "ClassNotFoundException" + e.getLocalizedMessage());}
catch ( NoSuchMethodException e ) {Log.e(TAG, "NoSuchMethodException" + e.getLocalizedMessage());}
catch ( NoSuchFieldException e ) {Log.e(TAG, "NoSuchFieldException" + e.getLocalizedMessage());}
catch ( IllegalAccessException e ) {Log.e(TAG, "IllegalAccessException" + e.getLocalizedMessage());}
catch ( InvocationTargetException e ) {Log.e(TAG, "InvocationTargetException" + e.getLocalizedMessage());}
catch ( InstantiationException e ) {Log.e(TAG, "InstantiationException" + e.getLocalizedMessage());}
catch ( SecurityException e ) {Log.e(TAG, "SecurityException" + e.getLocalizedMessage());}
catch ( NullPointerException e ) {Log.e(TAG, "NullPointerException" + e.getLocalizedMessage());}
if ( camera == null ) {
// Try using the pre-Gingerbread APIs to open the camera.
try {
camera = Camera.open();
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
return camera;
}
#Override
public void surfaceChanged(SurfaceHolder _holder, int _format, int _width, int _height) {
Camera.Parameters lParam = prCamera.getParameters();
prCamera.setParameters(lParam);
try {
prCamera.setPreviewDisplay(_holder);
prCamera.startPreview();
//prPreviewRunning = true;
} catch (IOException _le) {
_le.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
if(frontCamera == false)
{
prCamera = Camera.open();
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(), "Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}
}
else if(frontCamera == true)
{
try{
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
prCamera = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.i("Camera failed to open: ",e.getLocalizedMessage());
}
}
}
}catch(Exception e)
{
Toast.makeText(VideoCapture_New.this, "Your Device doesn't compatible for Fron Camera.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
try {
if (prRecordInProcess) {
stopRecording();
} else {
prCamera.stopPreview();
}
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private MediaRecorder prMediaRecorder;
private final int cMaxRecordDurationInMs = 30000;
private final long cMaxFileSizeInBytes = 5000000;
private final int cFrameRate = 20;
private File prRecordedFile;
private void updateEncodingOptions() {
if (prRecordInProcess) {
stopRecording();
startRecording();
Toast.makeText(prContext, "Recording restarted with new options!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(prContext, "Recording options updated!", Toast.LENGTH_SHORT).show();
}
}
private boolean startRecording() {
prCamera.stopPreview();
try {
prCamera.unlock();
prMediaRecorder.setCamera(prCamera);
prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
String lVideoFileFullPath=".mp4";
prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
String lDisplayMsg = "Current container format: ";
prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
lDisplayMsg += "Current encoding format: ";
lVideoFileFullPath = cVideoFilePath + "myvideo" + lVideoFileFullPath;
//prMediaRecorder.setOrientationHint(360);
prMediaRecorder.setVideoSize(176, 144);
prMediaRecorder.setVideoFrameRate(12);
prRecordedFile = new File(lVideoFileFullPath);
prMediaRecorder.setOutputFile(prRecordedFile.getPath());
prMediaRecorder.setVideoFrameRate(cFrameRate);
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
//prepare for capturing
//state: DataSourceConfigured => prepared
prMediaRecorder.prepare();
//start recording
//state: prepared => recording
prMediaRecorder.start();
//prStartBtn.setText("Stop");
prRecordInProcess = true;
return true;
} catch (IOException _le) {
_le.printStackTrace();
return false;
}
}
private void stopRecording() {
prMediaRecorder.stop();
prMediaRecorder.reset();
try {
prCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
//prStartBtn.setText("Start");
prRecordInProcess = false;
prCamera.startPreview();
}
private static final int REQUEST_DECODING_OPTIONS = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_DECODING_OPTIONS:
if (resultCode == RESULT_OK) {
updateEncodingOptions();
}
break;
}
}
}
I had the same problem and this little snipped fixed it
Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
Camera.getCameraInfo(0, info);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
this.mRotation = result;
mCamera.setDisplayOrientation(result);
I am not sure why it doesn't start at the current phone orientation but I am sure this fixes it.

android front facing camera problems

well, I am trying to develop an app that films with the front facing camera.
and i am having a wierd bug. the preview looks fine, but the output video comes out with a green line in low resolutions and broken with green lines in high resolutions
this is the code:
package feipeng.yacamcorder;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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.media.MediaRecorder.AudioEncoder;
import android.media.MediaRecorder.VideoEncoder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
/***
* TODO: 1. sound on/off 2. resolution change
*
* #author roman10
*
*/
public class Main extends Activity implements SurfaceHolder.Callback {
private SurfaceView prSurfaceView;
private Button prStartBtn;
private Button prSettingsBtn;
private boolean prRecordInProcess;
private SurfaceHolder prSurfaceHolder;
private Camera prCamera;
private final String cVideoFilePath = "/sdcard/r10videocam/";
private Context prContext;
private MediaRecorder prMediaRecorder;
private CamcorderProfile mProfile;
private final int cMaxRecordDurationInMs = 30000;
private final long cMaxFileSizeInBytes = 5000000;
private final int cFrameRate = 20;
private File prRecordedFile;
private static final int REQUEST_DECODING_OPTIONS = 0;
private static final String TAG = "aaa";
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_DECODING_OPTIONS:
if (resultCode == RESULT_OK) {
updateEncodingOptions();
}
break;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
prContext = this.getApplicationContext();
setContentView(R.layout.main);
Utils.createDirIfNotExist(cVideoFilePath);
prSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
prStartBtn = (Button) findViewById(R.id.main_btn1);
prSettingsBtn = (Button) findViewById(R.id.main_btn2);
prRecordInProcess = false;
prStartBtn.setOnClickListener(new View.OnClickListener() {
// #Override
#Override
public void onClick(View v) {
if (prRecordInProcess == false) {
startRecording();
} else {
stopRecording();
}
}
});
prSettingsBtn.setOnClickListener(new View.OnClickListener() {
// #Override
#Override
public void onClick(View v) {
Intent lIntent = new Intent();
lIntent.setClass(prContext,
feipeng.yacamcorder.SettingsDialog.class);
startActivityForResult(lIntent, REQUEST_DECODING_OPTIONS);
}
});
prSurfaceHolder = prSurfaceView.getHolder();
prSurfaceHolder.addCallback(this);
prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
prMediaRecorder = new MediaRecorder();
}
private Camera openFrontFacingCamera() {
Camera camera = null;
// Look for front-facing camera, using the Gingerbread API.
// Java reflection is used for backwards compatibility with
// pre-Gingerbread APIs.
try {
Class<?> cameraClass = Class.forName("android.hardware.Camera");
Object cameraInfo = null;
Field field = null;
int cameraCount = 0;
Method getNumberOfCamerasMethod = cameraClass
.getMethod("getNumberOfCameras");
if (getNumberOfCamerasMethod != null) {
cameraCount = (Integer) getNumberOfCamerasMethod.invoke(null,
(Object[]) null);
}
Class<?> cameraInfoClass = Class
.forName("android.hardware.Camera$CameraInfo");
if (cameraInfoClass != null) {
cameraInfo = cameraInfoClass.newInstance();
}
if (cameraInfo != null) {
field = cameraInfo.getClass().getField("facing");
}
Method getCameraInfoMethod = cameraClass.getMethod("getCameraInfo",
Integer.TYPE, cameraInfoClass);
if (getCameraInfoMethod != null && cameraInfoClass != null
&& field != null) {
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
getCameraInfoMethod.invoke(null, camIdx, cameraInfo);
int facing = field.getInt(cameraInfo);
if (facing == 1) { // Camera.CameraInfo.CAMERA_FACING_FRONT
try {
Method cameraOpenMethod = cameraClass.getMethod(
"open", Integer.TYPE);
if (cameraOpenMethod != null) {
camera = (Camera) cameraOpenMethod.invoke(null,
camIdx);
mProfile = CamcorderProfile
.get(CamcorderProfile.QUALITY_LOW);
}
} catch (RuntimeException e) {
Log.e(TAG,
"Camera failed to open: "
+ e.getLocalizedMessage());
}
}
}
}
}
// Ignore the bevy of checked exceptions the Java Reflection API throws
// - if it fails, who cares.
catch (ClassNotFoundException e) {
Log.e(TAG, "ClassNotFoundException" + e.getLocalizedMessage());
} catch (NoSuchMethodException e) {
Log.e(TAG, "NoSuchMethodException" + e.getLocalizedMessage());
} catch (NoSuchFieldException e) {
Log.e(TAG, "NoSuchFieldException" + e.getLocalizedMessage());
} catch (IllegalAccessException e) {
Log.e(TAG, "IllegalAccessException" + e.getLocalizedMessage());
} catch (InvocationTargetException e) {
Log.e(TAG, "InvocationTargetException" + e.getLocalizedMessage());
} catch (InstantiationException e) {
Log.e(TAG, "InstantiationException" + e.getLocalizedMessage());
} catch (SecurityException e) {
Log.e(TAG, "SecurityException" + e.getLocalizedMessage());
}
if (camera == null) {
// Try using the pre-Gingerbread APIs to open the camera.
try {
camera = Camera.open();
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
return camera;
}
private boolean startRecording() {
prCamera.stopPreview();
try {
prCamera.unlock();
prMediaRecorder.setCamera(prCamera);
// set audio source as Microphone, video source as camera
// state: Initial=>Initialized
prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// set the file output format: 3gp or mp4
// state: Initialized=>DataSourceConfigured
String lVideoFileFullPath;
String lDisplayMsg = "Current container format: ";
if (Utils.puContainerFormat == SettingsDialog.cpu3GP) {
lDisplayMsg += "3GP\n";
lVideoFileFullPath = ".3gp";
prMediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
} else if (Utils.puContainerFormat == SettingsDialog.cpuMP4) {
lDisplayMsg += "MP4\n";
lVideoFileFullPath = ".mp4";
prMediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
} else {
lDisplayMsg += "3GP\n";
lVideoFileFullPath = ".3gp";
prMediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
}
// the encoders:
// audio: AMR-NB
prMediaRecorder.setAudioEncoder(AudioEncoder.AMR_NB);
// video: H.263, MP4-SP, or H.264
// prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
// prMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP);
lDisplayMsg += "Current encoding format: ";
if (Utils.puEncodingFormat == SettingsDialog.cpuH263) {
lDisplayMsg += "H263\n";
prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
} else if (Utils.puEncodingFormat == SettingsDialog.cpuMP4_SP) {
lDisplayMsg += "MPEG4-SP\n";
prMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP);
} else if (Utils.puEncodingFormat == SettingsDialog.cpuH264) {
lDisplayMsg += "H264\n";
prMediaRecorder.setVideoEncoder(VideoEncoder.H264);
} else {
lDisplayMsg += "H263\n";
prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
}
lVideoFileFullPath = cVideoFilePath
+ String.valueOf(System.currentTimeMillis())
+ lVideoFileFullPath;
prRecordedFile = new File(lVideoFileFullPath);
prMediaRecorder.setOutputFile(prRecordedFile.getPath());
if (Utils.puResolutionChoice == SettingsDialog.cpuRes176) {
prMediaRecorder.setVideoSize(176, 144);
} else if (Utils.puResolutionChoice == SettingsDialog.cpuRes320) {
prMediaRecorder.setVideoSize(320, 240);
} else if (Utils.puResolutionChoice == SettingsDialog.cpuRes720) {
prMediaRecorder.setVideoSize(720, 480);
}
Toast.makeText(prContext, lDisplayMsg, Toast.LENGTH_LONG).show();
prMediaRecorder.setVideoFrameRate(cFrameRate);
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
// prepare for capturing
// state: DataSourceConfigured => prepared
prMediaRecorder.prepare();
// start recording
// state: prepared => recording
prMediaRecorder.start();
prStartBtn.setText("Stop");
prRecordInProcess = true;
return true;
} catch (IOException _le) {
_le.printStackTrace();
return false;
}
}
private void stopRecording() {
prMediaRecorder.stop();
prMediaRecorder.reset();
try {
prCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
prStartBtn.setText("Start");
prRecordInProcess = false;
prCamera.startPreview();
}
// #Override
#Override
public void surfaceChanged(SurfaceHolder _holder, int _format, int _width,
int _height) {
Camera.Parameters lParam = prCamera.getParameters();
// //lParam.setPreviewSize(_width, _height);
// //lParam.setPreviewSize(320, 240);
// lParam.setPreviewFormat(PixelFormat.JPEG);
prCamera.setParameters(lParam);
try {
prCamera.setPreviewDisplay(_holder);
prCamera.startPreview();
// prPreviewRunning = true;
} catch (IOException _le) {
_le.printStackTrace();
}
}
// #Override
#Override
public void surfaceCreated(SurfaceHolder arg0) {
prCamera = openFrontFacingCamera();
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}
}
// #Override
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
if (prRecordInProcess) {
stopRecording();
} else {
prCamera.stopPreview();
}
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
}
private void updateEncodingOptions() {
if (prRecordInProcess) {
stopRecording();
startRecording();
Toast.makeText(prContext, "Recording restarted with new options!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(prContext, "Recording options updated!",
Toast.LENGTH_SHORT).show();
}
}
}
p.s.
using galaxy s1.
any ideas?
I tried your code on Samsung Nexus S running on 4.0.4 and it works well.
The MediaRecorder was set as follows:
private boolean startRecording() {
...
prMediaRecorder.setCamera(prCamera);
prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
prMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
prMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
prMediaRecorder.setOutputFile("/sdcard/video.mp4");
prMediaRecorder.setVideoSize(320, 240);//If higher produces error -19
prMediaRecorder.setVideoFrameRate(15);//If higher produces error -19
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
prMediaRecorder.prepare();
prMediaRecorder.start();
...
}//endOfStartRecording()
For a 10 sec recording it produces a .mp4 file of ~300 KB size. The quality is not really great but it is the highest I could get. Have in mind that the front facing camera is not as powerful as the back one.

Categories

Resources