I am working in camera. I use toggle camera. When I record video in back camera then every think is OK, but when I use front camera I have illegalstateexception. I try to change my stopRecording() method, but nothing changed.
This is a my source
prSurfaceHolder = prSurfaceView.getHolder();
prSurfaceHolder.addCallback(this);
prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
toogleCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (choose == false) {
try {
toggleCamera();
} catch (IOException e) {
e.printStackTrace();
}
choose = true;
} else {
try {
BackCamera();
} catch (IOException e) {
e.printStackTrace();
}
choose = false;
}
}
});
public void toggleCamera() throws IOException {
prCamera.stopPreview();
int frontCameraId = 0;
for (int camNo = 0; camNo < Camera.getNumberOfCameras(); camNo++) {
CameraInfo camInfo = new CameraInfo();
Camera.getCameraInfo(camNo, camInfo);
if (camInfo.facing == (Camera.CameraInfo.CAMERA_FACING_FRONT)) {
frontCameraId = camNo;
}
}
prCamera.release();
// Log.d(TAG + "Restarting camera", ""+frontCameraId);
prCamera = Camera.open(frontCameraId);
// added code
prCamera.setPreviewDisplay(prSurfaceHolder);
// prCamera.setPreviewCallback([reference to your Camera.PreviewCallback
// object]);
// end added code
prCamera.startPreview();
// Log.d(TAG + "Restarting camera", ""+frontCameraId);
}
public void BackCamera() throws IOException {
prCamera.stopPreview();
int frontCameraId = 0;
for (int camNo = 0; camNo < Camera.getNumberOfCameras(); camNo++) {
CameraInfo camInfo = new CameraInfo();
Camera.getCameraInfo(camNo, camInfo);
if (camInfo.facing == (Camera.CameraInfo.CAMERA_FACING_BACK)) {
frontCameraId = camNo;
}
}
prCamera.release();
// Log.d(TAG + "Restarting camera", ""+frontCameraId);
prCamera = Camera.open(frontCameraId);
// added code
prCamera.setPreviewDisplay(prSurfaceHolder);
// prCamera.setPreviewCallback([reference to your Camera.PreviewCallback
// object]);
// end added code
prCamera.startPreview();
// Log.d(TAG + "Restarting camera", ""+frontCameraId);
}
#Override
public void surfaceChanged(SurfaceHolder _holder, int _format, int _width,
int _height) {
try {
if (prCamera == null)
return;
prCamera.setPreviewDisplay(_holder);
prCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
CameraInfo cameraInfo = new CameraInfo();
int cameraCount = Camera.getNumberOfCameras();
if (cameraCount > 1)
for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
try {
prCamera = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.i("Camera failed to open: ",
e.getLocalizedMessage());
}
}
}
else
prCamera = Camera.open();
if (prCamera == null) {
Toast.makeText(this, "Camera is not available!", Toast.LENGTH_SHORT)
.show();
finish();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (prCamera != null) {
prCamera.stopPreview();
prCamera.stopPreview();
prCamera.release();
prCamera = null;
}
}
protected void startRecording() throws IOException {
prMediaRecorder = new MediaRecorder();
prCamera.unlock();
prMediaRecorder.setCamera(prCamera);
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
prMediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH));
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
prMediaRecorder.setOutputFile(mVideoFilename);
prMediaRecorder.prepare();
prMediaRecorder.start();
}
private void stopRecording() {
if (prMediaRecorder != null) {
prMediaRecorder.stop();
timer.cancel();
prMediaRecorder.reset();
prMediaRecorder.release();
video_start_timer.setText("00:15");
}
}
I have no idea what i am doing wrong.
If anyone knows solution please help me.
Related
Is there any way to get photo without preview and put it to database in android sdk 19
In the below code automaticly getting location on every 5 minutes and putting marker on map additionally i need to take photo automaticly and put it to database
public void startCountDown() {
if (this._countDownTimer != null) {
this._countDownTimer.cancel();
}
_countDownTimer = new CountDownTimer(60000 * 5, 60000*5) {
#Override
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
putMarkerToLocation();
takePhotoAndSaveIt2Db(); // ==> here what i need
}
}.start();
}
Below service works percfectly on api19
public class CapPhoto extends Service {
private Camera mCamera;
#Override
public void onCreate() {
super.onCreate();
Log.d("CAM", "start");
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Thread myThread = null;
}
#Override
public void onStart(Intent intent, int startId) {
takePhoto();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void takePhoto() {
System.out.println("Fotoraf Cekimi Hazirligi Basladi");
Camera camera = null;
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
SystemClock.sleep(1000);
Camera.getCameraInfo(camIdx, cameraInfo);
try {
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
System.out.println("Camera not available: " + camIdx);
camera = null;
//e.printStackTrace();
}
try {
if (null == camera) {
System.out.println("Could not get camera instance");
} else {
System.out.println("Got the camera, creating the dummy surface texture");
//SurfaceTexture dummySurfaceTextureF = new SurfaceTexture(0);
try {
//camera.setPreviewTexture(dummySurfaceTextureF);
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
} catch (Exception e) {
System.out.println("Could not set the surface preview texture");
e.printStackTrace();
}
camIdx = cameraCount;
Camera.Parameters params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
params.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
params.setExposureCompensation(0);
params.setPictureFormat(ImageFormat.JPEG);
params.setJpegQuality(100);
params.setRotation(90);
camera.setParameters(params);
camera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir =new File(Environment.getExternalStorageDirectory(), "A");
if(!pictureFileDir.exists()){
pictureFileDir.mkdirs();
} // File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "TaksiResim_" + "_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File mainPicture = new File(filename);
//addImageFile(mainPicture);
try {
FileOutputStream fos = new FileOutputStream(mainPicture);
fos.write(data);
fos.close();
System.out.println("resim kayit edildi");
} catch (Exception error) {
System.out.println("resim kayit edilemedi");
}
camera.release();
}
});
}
} catch (Exception e) {
camera.release();
}
}
} }
I want to make an app that record video, it seems like vine, hold to record, release it stop, hold to record and keep that to the end.
I have used MediaRecorder, but it just record once a time, if I start record again, app is crashed.
Please tell me there is any way to do this?
I edited my code:
public class VideoRecordingActivity extends AppCompatActivity implements View.OnTouchListener, View.OnLongClickListener {
private Context myContext;
private boolean hasCamera;
private boolean onRecording;
private Camera mCamera;
private CameraPreview mPreview;
private MediaRecorder mediaRecorder;
private boolean cameraFront = false;
private int cameraId;
private int videoNumer;
private boolean isActionDown = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_introduction_recording);
initUI();
initialize();
}
private LinearLayout lnCameraPreview;
private ImageButton btn_recording;
private void initUI() {
lnCameraPreview = (LinearLayout) findViewById(R.id.ln_body_recording);
btn_recording = (ImageButton) findViewById(R.id.btn_recording);
}
public void initialize() {
myContext = this;
mPreview = new CameraPreview(this, cameraId, mCamera);
lnCameraPreview.addView(mPreview);
btn_recording.setOnLongClickListener(this);
btn_recording.setOnTouchListener(this);
videoNumer = 0;
}
public boolean onLongClick(View v) {
isActionDown = true;
try {
boolean isPrepared = false;
if (isActionDown)
isPrepared = prepareMediaRecorder();
if (isPrepared && isActionDown) {
// work on UiThread for better performance
runOnUiThread(new Runnable() {
public void run() {
mediaRecorder.start();
onRecording = true;
}
});
}
} catch (Exception e) {
e.printStackTrace();
Log.e("onLongPress Error ", e.toString());
}
return true;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
isActionDown = false;
try {
if (onRecording) {
if (mediaRecorder != null) {
mediaRecorder.stop();
}
onRecording = false;
videoNumer++;
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return false;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG).show();
return;
}
initCamera();
}
#Override
protected void onPause() {
super.onPause();
// when on Pause, release camera in order to be used from other
// applications
releaseCamera();
}
private final int cMaxRecordDurationInMs = 30000;
private final long cMaxFileSizeInBytes = 5000000;
private final int cFrameRate = 20;
private File prRecordedFile;
#SuppressLint("SdCardPath")
private boolean prepareMediaRecorder() {
mediaRecorder = new MediaRecorder();
try {
mCamera.unlock();
} catch (Exception ex) {
return false;
}
// adjust the camera the way you need
mediaRecorder.setCamera(mCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
//
CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
mediaRecorder.setProfile(cpHigh);
mediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mediaRecorder.setOutputFile("/sdcard/" + videoNumer + "videocapture_example.mp4");
//set max size
mediaRecorder.setMaxDuration(600000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M
try {
mediaRecorder.prepare();
} catch (Exception e) {
releaseMediaRecorder();
e.printStackTrace();
}
return true;
}
private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
if (mCamera != null) {
mCamera.lock(); // lock camera for later use
}
}
}
/**
* Camera
*/
private void initCamera() {
if (mCamera == null) {
// if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
}
mCamera = Camera.open(findBackFacingCamera());
mPreview.refreshCamera(mCamera);
}
onRecording = false;
}
private boolean hasCamera(Context context) {
// check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
hasCamera = true;
} else {
hasCamera = false;
}
return hasCamera;
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
this.cameraId = cameraId;
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
// Search for the back facing camera
// get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
// for every camera check
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
this.cameraId = cameraId;
return cameraId;
}
public void switchCamera() {
// if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
// open the backFacingCamera
mCamera = Camera.open(cameraId);
// refresh the preview
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
// open the backFacingCamera
mCamera = Camera.open(cameraId);
// refresh the preview
mPreview.refreshCamera(mCamera);
}
}
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}
You can do achieve this functionality by setting OnLongClickListener() and OnTouchListener() on your record button. Like this:
recordBtn.setOnLongClickListener(recordBtnLCListener);
recordBtn.setOnTouchListener(recordBtnTouchListener);
then :
#Override
public boolean onLongClick(View v) {
ivCancel.setVisibility(View.GONE);
ivDone.setVisibility(View.GONE);
isActionDown = true;
try {
if (isActionDown) {
initRecorder();
if (isActionDown)
prepareRecorder();
}
if (isPrepared && isActionDown) {
mMediaRecorder.start();
isRecording = true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("onLongPress Error ", e.toString());
}
return true;
}
and :
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
isActionDown = false;
try {
if (isRecording) {
if (mMediaRecorder != null) {
mMediaRecorder.stop();
}
isRecording = false;
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
return false;
}
So, in this way you can record the parts of video.Means each time you LongPress your record button, the recording starts. And time you release the button, the recording stops and here you have to save this part of video in any temporary folder.
Once you done taking all parts of videos as many as you want, then you have to combine all that parts of videos to make a single video.
Here, is the code to merge all that video parts saved in temperory folder:
public void mergeVideos() {
try {
List<Movie> inMovies = new ArrayList<>();
for (int i = 0; i < videosPathList.size(); i++) {
String filePath = videosPathList.get(i);
try {
Movie movie = MovieCreator.build(filePath);
if (movie != null)
inMovies.add(movie);
} catch (Exception e) {
e.printStackTrace();
}
}
List<Track> videoTracks = new LinkedList<Track>();
List<Track> audioTracks = new LinkedList<Track>();
for (Movie m : inMovies) {
for (Track t : m.getTracks()) {
try {
if (t.getHandler().equals("soun")) {
audioTracks.add(t);
}
if (t.getHandler().equals("vide")) {
videoTracks.add(t);
}
} catch (Exception e) {
}
}
}
Movie result = new Movie();
if (audioTracks.size() > 0) {
result.addTrack(new AppendTrack(audioTracks
.toArray(new Track[audioTracks.size()])));
}
if (videoTracks.size() > 0) {
result.addTrack(new AppendTrack(videoTracks
.toArray(new Track[videoTracks.size()])));
}
BasicContainer out = (BasicContainer) new DefaultMp4Builder().build(result);
File f = null;
String finalVideoPath;
try {
f = setUpVideoFile(Environment
.getExternalStorageDirectory()+"/MyApp/videos/");
finalVideoPath = f.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
f = null;
finalVideoPath = null;
}
WritableByteChannel fc = new RandomAccessFile(finalVideoPath, "rw").getChannel();
out.writeContainer(fc);
fc.close();
deleteFilesDir(); //In this method you have to delete all parts of video stored in temporary folder.
} catch (Exception e) {
e.printStackTrace();
progressDialog.dismiss();
finish();
}
}
File setUpVideoFile(String directory) throws IOException {
File videoFile = null;
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
File storageDir = new File(directory);
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
videoFile = File.createTempFile("video_"
+ System.currentTimeMillis() + "_",
.mp4, storageDir);
}
return videoFile;
}
You can call mergeVideos() method after stopping mediaRecorder.
Hope this code helps you. :)
For merging the videos you have to use the isoparser library. So you have to add following dependendy in your gradle file :
compile 'com.googlecode.mp4parser:isoparser:1.0.5.4'
This is my code.
public class VideoRecordingActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
private boolean isPrepared = false;
int videoNumber = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
super.onCreate(savedInstanceState);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.activity_video_introduction_recording);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.ln_body_recording);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
}
private void initRecorder() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraSample");
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
//CGlobal.VIDEO_RECORD_PATH = CGlobal.VIDEO_HOME_PATH + "VID_" + timeStamp;
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
recorder.setOutputFile(mediaFile+".mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
isPrepared = true;
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
isPrepared = false;
videoNumber++;
// Let's initRecorder so we can record again
} else {
if (!isPrepared){
initRecorder();
prepareRecorder();
}
recording = true;
recorder.start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
}
I want to implement touch to focus on my custom camera here is my code for custom camera . I know android api 14 level support focus and its also hardware dependent so any one have idea how to implement it.
private SurfaceView previewSv;
private ImageButton stillImgCamIb, videoCamIb, galleryIb;
private TextView cancelTv;
private Handler handler = new Handler();
private Camera camera;
private int cameraId = 0;
private boolean cameraFlash = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean hasCameraFlash = getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH);
boolean hasFrontCam = getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT);
previewSv = (SurfaceView) findViewById(R.id.preview_sv);
stillImgCamIb = (ImageButton) findViewById(R.id.still_img_camera_ib);
videoCamIb = (ImageButton) findViewById(R.id.video_camera_ib);
galleryIb = (ImageButton) findViewById(R.id.gallery_ib);
cancelTv = (TextView) findViewById(R.id.cancel_tv);
stillImgCamIb.setOnClickListener(this);
videoCamIb.setOnClickListener(this);
galleryIb.setOnClickListener(this);
cancelTv.setOnClickListener(this);
startCameraPreview();
}
#Override
protected void onStop() {
super.onStop();
stopCameraPreview();
stopRecording();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.still_img_camera_ib:
if (mode == Mode.STILL_CAMERA) {
if (previewing) {
handleStillCamClick();
}
} else if (mode == Mode.VIDEO_CAMERA) {
stopCameraPreview();
startRecording();
activateMode(Mode.RECORDING);
} else if (mode == Mode.RECORDING) {
stopRecording();
activateMode(Mode.VIDEO_CAMERA);
} else {
activateMode(Mode.STILL_CAMERA);
}
break;
case R.id.video_camera_ib:
if (mode == Mode.VIDEO_CAMERA) {
activateMode(Mode.STILL_CAMERA);
} else {
activateMode(Mode.VIDEO_CAMERA);
}
break;
case R.id.gallery_ib:
// openGallery();
break;
case R.id.cancel_tv:
activateMode(Mode.VIDEO_CAMERA);
stopRecording();
break;
default:
break;
}
}
private Uri capturedImageUri;
private boolean previewing = false;
private void startCameraPreview() {
if (!previewing) {
previewing = true;
camera = Camera.open(cameraId);
camera.getParameters().setFlashMode(
cameraFlash ? Parameters.FLASH_MODE_ON
: Parameters.FLASH_MODE_OFF);
camera.setDisplayOrientation(90);
if (camera != null) {
try {
System.out.println("Started camera preview!");
camera.setPreviewDisplay(previewSv.getHolder());
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
previewSv.getHolder().addCallback(new Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
stopCameraPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
if (previewing) {
stopCameraPreview();
}
startCameraPreview();
}
});
}
private void stopCameraPreview() {
if (camera != null && previewing) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
private void handleStillCamClick() {
if (camera != null) {
Parameters params = camera.getParameters();
Size defaultSize = params.getPictureSize();
System.out.println("Default size X:" + defaultSize.width + ", Y:"
+ defaultSize.height);
// Loop over supported sizes and pick one that is larger than 640px
// wide & tall, only if the default size is too small
if (defaultSize.width < 640 || defaultSize.height < 640) {
List<Size> sizes = params.getSupportedPictureSizes();
// int biggestH = 0;
// int biggestW = 0;
int maxH = Integer.MAX_VALUE;
int maxW = Integer.MAX_VALUE;
for (int i = 0; i < sizes.size(); i++) {
Size thisSize = sizes.get(i);
int thisW = thisSize.width;
int thisH = thisSize.height;
boolean betterWidth = thisW < maxW && thisW >= 1000;
boolean betterHeight = thisH < maxH && thisH >= 1000;
boolean isFourThreeAspect = thisW == (4 * thisH / 3);
if (isFourThreeAspect) {
System.out.println("Supports size: W" + thisSize.width
+ ", H:" + thisSize.height);
} else {
System.out.println("not 4/3, but Supports size: W"
+ thisSize.width + ", H:" + thisSize.height);
}
if (betterWidth && betterHeight && isFourThreeAspect) {
maxH = thisH;
maxW = thisW;
}
}
if (maxH < 99999 && maxW < 99999) {
System.out.println("Found best size, W:" + maxW + ", H:"
+ maxH);
Toast.makeText(
this,
"Taking picture at resolution:" + maxW + "x" + maxH,
Toast.LENGTH_LONG).show();
params.setPictureSize(maxW, maxH);
} else {
System.out
.println("Couldn't find best size! Going with default");
}
camera.setParameters(params);
} else {
}
camera.takePicture(new ShutterCallback() {
#Override
public void onShutter() {
}
}, null, new PictureCallback() {
public void onPictureTaken(byte[] bytes, Camera camera) {
System.out
.println("got jpeg bytes, length:" + bytes.length);
stopCameraPreview();
}
});
}
}
public MediaRecorder mediaRecorder = new MediaRecorder();
private boolean recording = false;
protected void startRecording() {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath().toString();
String filename = "/xyz.mp4";
mediaRecorder = new MediaRecorder();
camera = Camera.open(cameraId);
camera.getParameters().setFlashMode(
cameraFlash ? Parameters.FLASH_MODE_AUTO
: Parameters.FLASH_MODE_OFF);
camera.setDisplayOrientation(90);
Log.d("TabCustomCameraFragment", "startRecording - Camera.open");
camera.lock();
camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH));
mediaRecorder.setVideoSize(640, 640);
mediaRecorder.setPreviewDisplay(previewSv.getHolder().getSurface());
mediaRecorder.setOutputFile(path + filename);
if (isVertical()) {
mediaRecorder.setOrientationHint(cameraId == 0 ? 90 : 270);
} else {
mediaRecorder.setOrientationHint(cameraId == 0 ? 90 : 180);
}
mediaRecorder.setMaxDuration(10000);
try {
camera.stopPreview();
mediaRecorder.prepare();
mediaRecorder.start();
recording = true;
remainingCaptureTime = MAX_VIDEO_DURATION;
updateRemainingTime();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void stopRecording() {
if (mediaRecorder != null && recording) {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
camera.release();
recording = false;
handler.removeCallbacksAndMessages(null);
}
}
private int remainingCaptureTime;
private void updateRemainingTime() {
Log.d("TabCustomCameraFragment",
"updateRemainingTime - remainingCaptureTime="
+ remainingCaptureTime);
if (remainingCaptureTime <= 500) {
stopCameraPreview();
stopRecording();
return;
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
remainingCaptureTime -= 500;
updateRemainingTime();
}
}, 500);
}
private boolean isVertical() {
Display getOrient = getWindowManager().getDefaultDisplay();
if (getOrient.getWidth() <= getOrient.getHeight()) {
return true;
}
return false;
}
private enum Mode {
STILL_CAMERA, VIDEO_CAMERA, RECORDING;
}
private Mode mode = Mode.STILL_CAMERA;
private void activateMode(Mode mode) {
switch (mode) {
case STILL_CAMERA:
this.mode = Mode.STILL_CAMERA;
cancelTv.setVisibility(View.GONE);
galleryIb.setVisibility(View.VISIBLE);
videoCamIb.setVisibility(View.VISIBLE);
break;
case VIDEO_CAMERA:
this.mode = Mode.VIDEO_CAMERA;
stillImgCamIb.setImageResource(R.drawable.ic_launcher);
videoCamIb.setImageResource(R.drawable.ic_launcher);
cancelTv.setVisibility(View.GONE);
galleryIb.setVisibility(View.VISIBLE);
videoCamIb.setVisibility(View.VISIBLE);
break;
case RECORDING:
this.mode = Mode.RECORDING;
stillImgCamIb.setImageResource(R.drawable.ic_launcher);
cancelTv.setVisibility(View.VISIBLE);
galleryIb.setVisibility(View.GONE);
videoCamIb.setVisibility(View.GONE);
break;
default:
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
stopCameraPreview();
stopRecording();
}
How to change rear camera to front camera ?
public void setPreview() throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
mCamera.setPreviewTexture( new SurfaceTexture(10) );
else
mCamera.setPreviewDisplay(null);
}
How to change and use front camera ?
public boolean openCamera() {
Log.i(TAG, "openCamera");
releaseCamera();
mCamera = Camera.open();
if(mCamera == null) {
Log.e(TAG, "Can't open camera!");
return false;
}
}
How to change camera ?
public void releaseCamera() {
Log.i(TAG, "releaseCamera");
mThreadRun = false;
synchronized (this) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
onPreviewStopped();
}
you can use this method by passing boolean values for opening front camera true or false for back camera and please reset camera before calling this method.
private void opnenCamera(boolean isFront){
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && isFront ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}else if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK && !isFront ) {
try {
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
}
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.