前置摄像头的Android中 [英] Front camera in android
本文介绍了前置摄像头的Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做一个应用程序中,用户可以录制视频throuh定制的摄像头。和用户还可以通过前置摄像头录制视频。据记载罚款,但是当我们在正常的媒体播放器发挥了它在播放就在180度。我不知道这怎么可能,以及如何解决一样吗?请给我建议就同一任何解决方案。
code:
包com.irantapps.cameraApplication;进口的java.io.File;
进口java.io.IOException异常;进口android.annotation.Sup pressLint;
进口android.app.AlertDialog;
进口android.content.Context;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.database.Cursor;
进口android.hardware.Camera;
进口android.media.ExifInterface;
进口android.media.MediaPlayer;
进口android.media.MediaRecorder;
进口android.media.MediaRecorder.VideoEn codeR;
进口android.net.Uri;
进口android.os.Bundle;
进口android.os.Environment;
进口android.os.SystemClock;
进口android.provider.MediaStore;
进口android.util.Log;
进口android.view.KeyEvent;
进口android.view.Surface;
进口android.view.SurfaceHolder;
进口android.view.SurfaceView;
进口android.view.View;
进口android.view.Window;
进口android.view.animation.AlphaAnimation;
进口android.view.animation.Animation;
进口android.view.animation.LinearInterpolator;
进口android.widget.Button;
进口android.widget.Chronometer;
进口android.widget.ImageButton;
进口android.widget.LinearLayout;
进口android.widget.Toast;进口com.irantapps.AfterLoginHome;
进口com.irantapps.BaseActivity;
进口com.irantapps.CameraPlay_New;
进口com.irantapps.R;
进口com.irantapps.utility.DateAndLength;
进口com.irantapps.utility.VideoDetailsCollection;/ ***
* TODO:1,声音开/关2.决议变化
*
* @author roman10
*
* /公共类VideoCapture_New扩展BaseActivity工具
SurfaceHolder.Callback {
私人SurfaceView prSurfaceView;
私人的ImageButton prStartBtn,prFrontBackCamera;
私人按钮prSettingsBtn;
私人的ImageButton btn_Gallery;
公共字符串标记=IRANT;
私人布尔prRecordInProcess;
私人SurfaceHolder prSurfaceHolder;
私人相机prCamera;
私人最终字符串cVideoFilePath =/ SD卡/;
天文台cm_VideoCapture;
私人语境prContext;
公共静态布尔frontCamera = FALSE;
INT mRotation;
的LinearLayout linearLayoutRedbtn;
的ImageButton BTN;
动画动画;
的ImageButton btn_Cancel;
DateAndLength findDateandLength;
私人VideoDetailsCollection videoDetails = VideoDetailsCollection.getSingletonObject();
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE);
prContext = this.getApplicationContext();
的setContentView(R.layout.videocapture_new);
Utils.createDirIfNotExist(cVideoFilePath);
findDateandLength = DateAndLength.getSingletonObject();
动画=新AlphaAnimation(1,0); //从完全可见更改阿尔法
//为不可见
animation.setDuration(500); //时间 - 半秒
animation.setInterpolator(新LinearInterpolator()); //不改变
//动画
//率
animation.setRepeatCount(Animation.INFINITE); //重复动画
//无限
animation.setRepeatMode(Animation.REVERSE); //在反向动画
//最终使按键会
//渐退的
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(新View.OnClickListener(){ @覆盖
公共无效的onClick(查看为arg0){
// TODO自动生成方法存根
如果(prRecordInProcess == FALSE){
cm_VideoCapture.setBase(SystemClock.elapsedRealtime());
//cm_VideoCapture.clearComposingText(); cm_VideoCapture.start();
尝试{
的StartRecording();
}赶上(NoSuchMethodException E){
// TODO自动生成catch块
e.printStackTrace();
}
linearLayoutRedbtn.startAnimation(动画);
}其他{
STO precording();
linearLayoutRedbtn.clearAnimation();
cm_VideoCapture.stop();
findDateandLength.setTimeLengthOfVideo(cm_VideoCapture.getText()的toString());
//Toast.makeText(getApplicationContext(),你好......+ cm_VideoCapture.getText(),Toast.LENGTH_LONG).show();
cm_VideoCapture.clearComposingText();
意向意图=新意图(VideoCapture_New.this,
CameraPlay_New.class);
startActivity(意向);
} }
});
btn_Gallery.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(查看为arg0){
// TODO自动生成方法存根
意向意图=新的Intent();
intent.setType(视频/ *);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(意向,选择视频),2);
}
});
cm_VideoCapture =(天文台)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 =(按钮)findViewById(R.id.main_btn2);
prRecordInProcess = FALSE;
prStartBtn.setOnClickListener(新View.OnClickListener(){
// @覆盖
公共无效的onClick(视图v){
如果(prRecordInProcess == FALSE){
cm_VideoCapture.setBase(SystemClock.elapsedRealtime());
//cm_VideoCapture.clearComposingText(); cm_VideoCapture.start();
尝试{
的StartRecording();
}赶上(NoSuchMethodException E){
// TODO自动生成catch块
e.printStackTrace();
}
}其他{
STO precording();
btn.clearAnimation();
cm_VideoCapture.stop();
cm_VideoCapture.clearComposingText();
意向意图=新意图(VideoCapture_New.this,
CameraPlay_New.class);
startActivity(意向);
}
}
}); prFrontBackCamera.setOnClickListener(新View.OnClickListener(){ @燮pressLint(NewApi)
@覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
// prCamera = openFrontFacingCameraGingerbread();
尝试{
如果(Camera.getNumberOfCameras()== 2){
如果(frontCamera){
frontCamera = FALSE;
prCamera.stop preVIEW();
prMediaRecorder.release();
prMediaRecorder = NULL;
prCamera.release();
prCamera = NULL;
}其他{ frontCamera = TRUE;
prCamera.stop preVIEW();
prMediaRecorder.release();
prMediaRecorder = NULL;
prCamera.release();
prCamera = NULL;
}
意向意图=新意图(VideoCapture_New.this,
VideoCapture_New.class);
startActivity(意向);
}其他{
Toast.makeText(VideoCapture_New.this,
您的设备不包含前置摄像头。
Toast.LENGTH_SHORT).show();
}
}赶上(例外五){
e.printStackTrace();
Toast.makeText(VideoCapture_New.this,
您的设备不适合接待相机兼容。
Toast.LENGTH_SHORT).show(); } }
}); prSurfaceHolder = prSurfaceView.getHolder();
prSurfaceHolder.addCallback(本);
prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// prCamera.setDisplayOrientation(90);
prMediaRecorder =新MediaRecorder(); btn_Cancel.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(查看为arg0){
// TODO自动生成方法存根
完();
}
});
} @覆盖
公共无效surfaceChanged(SurfaceHolder _holder,诠释_format,INT _width,
INT _height){
Camera.Parameters的lParam = prCamera.getParameters(); prCamera.setParameters(lParam的);
尝试{
prCamera.set previewDisplay(_holder);
prCamera.start preVIEW();
// PR previewRunning = TRUE;
}赶上(IOException异常_le){
_le.printStackTrace();
}
} @燮pressLint({NewApi,NewApi,NewApi,NewApi,NewApi,NewApi,NewApi,NewApi,NewApi,NewApi,NewApi ,NewApi})
@覆盖
公共无效surfaceCreated(SurfaceHolder为arg0){
如果(frontCamera ==假放;&安培; prCamera == NULL){
/ * prCamera = Camera.open();
如果(prCamera == NULL){
Toast.makeText(this.getApplicationContext(),
相机是不可用!,Toast.LENGTH_SHORT).show();
完();
} * /
prCamera = Camera.open();
尝试{
prCamera.set previewDisplay(为arg0); // TODO试多少套previewCallbackWithBuffer更快
//prCamera.set$p$pviewCallback(VideoCapture_New.this);
}赶上(IOException异常五){
prCamera.release();
prCamera = NULL;
} 如果(prCamera == NULL){
Toast.makeText(this.getApplicationContext(),
相机是不可用!,Toast.LENGTH_SHORT).show();
完();
}
}
/ *否则,如果(prCamera == NULL){
prCamera = Camera.open();
尝试{
prCamera.set previewDisplay(为arg0); // TODO试多少套previewCallbackWithBuffer更快
//prCamera.set$p$pviewCallback(VideoCapture_New.this);
}赶上(IOException异常五){
prCamera.release();
prCamera = NULL;
} 如果(prCamera == NULL){
Toast.makeText(this.getApplicationContext(),
相机是不可用!,Toast.LENGTH_SHORT).show();
完();
}
} * /否则,如果(prCamera!= NULL){
prCamera.stop preVIEW();
prCamera.release();
prCamera = NULL;
} 否则,如果(frontCamera ==真){
尝试{
INT cameraCount = 0;
Camera.CameraInfo cameraInfo =新Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
对(INT camIdx = 0; camIdx&下; cameraCount; camIdx ++){
Camera.getCameraInfo(camIdx,cameraInfo);
如果(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
尝试{
prCamera = Camera.open(camIdx);
}赶上(RuntimeException的E){
Log.i(相机无法打开,
e.getLocalizedMessage());
}
}
}
}赶上(例外五){
Toast.makeText(VideoCapture_New.this,
您的设备不用于弗朗相机兼容。
Toast.LENGTH_SHORT).show();
}
}
尝试{
Camera.CameraInfo信息=新android.hardware.Camera.CameraInfo();
Camera.getCameraInfo(0,信息);
INT旋转= getWindowManager()getDefaultDisplay()getRotation()。
INT度= 0;
开关(旋转){
案例Surface.ROTATION_0:
度= 0;
打破;
案例Surface.ROTATION_90:
度= 90;
打破;
案例Surface.ROTATION_180:
度= 180;
打破;
案例Surface.ROTATION_270:
度= 270;
打破;
}
INT结果;
如果(info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
结果=(info.orientation +度)180%;
结果=(360 - 结果)%360; //补偿镜
}其他{//后置
结果=(info.orientation - 度+ 360)%360;
}
this.mRotation =结果;
prCamera.setDisplayOrientation(结果);
}赶上(NoClassDefFoundError的E){
// TODO自动生成catch块
e.printStackTrace();
prCamera.setDisplayOrientation(90);
Toast.makeText(VideoCapture_New.this,
有没有前置摄像头设备。Toast.LENGTH_SHORT)
。显示();
}
}
@覆盖
公共无效surfaceDestroyed(SurfaceHolder持有人){
如果(prCamera!= NULL){
prCamera.stop preVIEW();
prCamera.set previewCallback(NULL);
prCamera.release();
prCamera = NULL;
}
} / * @覆盖
公共无效surfaceDestroyed(SurfaceHolder为arg0){
尝试{
如果(prRecordInProcess){
STO precording();
}其他{
prCamera.stop preVIEW();
}
prMediaRecorder.release();
prMediaRecorder = NULL;
prCamera.release();
prCamera = NULL;
}赶上(例外五){
// TODO自动生成catch块
e.printStackTrace();
}
} * / 私人MediaRecorder prMediaRecorder;
私人最终诠释cMaxRecordDurationInMs = 30000;
私人最终长cMaxFileSizeInBytes = 5000000;
私人最终诠释cFrameRate = 20;
私人文件prRecordedFile; 私人无效updateEncodingOptions(){
如果(prRecordInProcess){
STO precording();
尝试{
的StartRecording();
}赶上(NoSuchMethodException E){
// TODO自动生成catch块
e.printStackTrace();
}
Toast.makeText(prContext,录音重启了新的选择!
Toast.LENGTH_SHORT).show();
}其他{
Toast.makeText(prContext,录音选项更新了!
Toast.LENGTH_SHORT).show();
}
} @燮pressLint(NewApi)
私人布尔的startRecording()抛出NoSuchMethodException {
prCamera.stop preVIEW();
尝试{
prCamera.unlock();
prMediaRecorder.setCamera(prCamera); prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
字符串lVideoFileFullPath =.MOV; prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
字符串lDisplayMsg =当前容器格式:;
prMediaRecorder.setAudioEn codeR(MediaRecorder.AudioEn coder.DEFAULT);
prMediaRecorder.setVideoEn codeR(VIDEOEN coder.H263);
prMediaRecorder.setOrientationHint(90); lDisplayMsg + =当前编码格式:; lVideoFileFullPath = Environment.getExternalStorageDirectory()+/myvideo.mp4;
// prMediaRecorder.setOrientationHint(360);
//prMediaRecorder.setVideoSize(176,144);
//prMediaRecorder.setVideoFrameRate(12);
prRecordedFile =新的文件(lVideoFileFullPath);
prMediaRecorder.setOutputFile(prRecordedFile.getPath()); //prMediaRecorder.setVideoFrameRate(cFrameRate);
prMediaRecorder.set previewDisplay(prSurfaceHolder.getSurface());
//prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
//prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
// prepare捕捉
//状态:DataSourceConfigured => prepared
prMediaRecorder prepare()。
//开始录制
//状态:prepared =>记录
prMediaRecorder.start();
// prStartBtn.setText(停止);
prRecordInProcess = TRUE;
ExifInterface exif_Video =新ExifInterface(lVideoFileFullPath); //由于API级别5
字符串exifOrientation_video = exif_Video.getAttribute(ExifInterface.TAG_ORIENTATION);
返回true;
}赶上(IOException异常_le){
_le.printStackTrace();
返回false;
}
} 私人无效STO precording(){
prMediaRecorder.stop();
prMediaRecorder.reset();
尝试{
prCamera.reconnect();
}赶上(IOException异常五){
e.printStackTrace();
}
// prStartBtn.setText(开始);
prRecordInProcess = FALSE;
prCamera.start preVIEW();
} 私有静态最终诠释REQUEST_DECODING_OPTIONS = 0; @覆盖
保护无效的onActivityResult(INT申请code,INT结果code,
意向意向){
super.onActivityResult(要求code,结果code,意向);
开关(要求code){
案例REQUEST_DECODING_OPTIONS:
如果(结果code == RESULT_OK){
updateEncodingOptions();
}
打破;
案例2:
如果(结果code == RESULT_OK){
// updateEncodingOptions();
如果(要求code == 2)
{
乌里selectedImageUri = intent.getData();
字符串selectedImagePath =的getPath(selectedImageUri);
的System.out.println(映像路径:+ selectedImagePath);
文件file_Video =新的文件(selectedImagePath);
MediaPlayer的熔点为新的MediaPlayer();
尝试{
mp.setDataSource(file_Video.getAbsolutePath());
videoDetails.setVideoPath(file_Video.getAbsolutePath());
如果(mp.getDuration()&下; = 3)
{
意图intentGallery =新意图(VideoCapture_New.this,CameraPlay_New.class);
startActivity(intentGallery);
}
其他
{
AlertDialog.Builder alertDialogBuilder =新AlertDialog.Builder(
本); //设置标题 alertDialogBuilder
.setTitle(信息);
//设置对话框消息
alertDialogBuilder
.setMessage(视频不能超过3分钟大。)
.setCancelable(假)
.setPositiveButton(OK,新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释的id){
//如果单击此按钮,关闭
// 目前的活动
dialog.cancel(); }
}); //创建警报对话框
AlertDialog alertDialog = alertDialogBuilder.create(); // 展示下
alertDialog.show();
}
}赶上(抛出:IllegalArgumentException五){
// TODO自动生成catch块
e.printStackTrace();
}赶上(IllegalStateException异常五){
// TODO自动生成catch块
e.printStackTrace();
}赶上(IOException异常五){
// TODO自动生成catch块
e.printStackTrace();
}
的System.out.println(视频长度:+ mp.getDuration()); }
//img.setImageURI(selectedImageUri);
}
打破;
}
}
公共字符串的getPath(URI URI){
的String [] =投影{MediaStore.Video.Media.DATA};
光标光标= managedQuery(URI,投影,NULL,NULL,NULL);
INT与Column_Index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
返回cursor.getString(Column_Index中);
}
@覆盖
公共布尔的onkeydown(INT键code,KeyEvent的事件){
如果(键code == KeyEvent.KEY code_BACK){ / *
*如果(崩溃==真|| collapse_cat ==真|| collapse_FuelEconomy ==真||
* collapse_LatestNews
* ==真|| collapse_price ==真|| collapse_RecentlyViwed ==真){
*意图restartResearchActivity =新
*意图(ResearchListNew.this,ResearchListNew.class);
* restartResearchActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
* startActivity(restartResearchActivity);
*
*}其他{完成(); }
* /
如果(prRecordInProcess == FALSE)
{
prCamera.lock();
}
其他
{
STO precording();
prCamera.lock();
} 意向意图=新意图(VideoCapture_New.this,
AfterLoginHome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(意向);
返回true;
}其他{ 返回super.onKeyDown(键code,事件);
} }
}
先谢谢了。
解决方案
新相机()setDisplayOrientation(90)。
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);
这篇关于前置摄像头的Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文