안 드 로 이 드 는 위 챗 을 모방 하여 작은 영상 을 녹화 했다.
먼저 사진 을 올 려 서 효 과 를 보 세 요.
간단히 서술 하 다
먼저 카메라 클래스 를 통 해 시스템 카 메 라 를 호출 합 니 다
**이번 버 전 은 전면 카메라 전환 비디오 녹화 문 제 를 업 데 이 트 했 습 니 다.
Android 일부 모 바 일 녹화 영상 IOS 모 바 일 문제(OPPO 모 바 일 부분 은 현재 사용 중인 H264 형식 에 맞지 않 음)**
완전한 코드
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.MediaMetadataRetriever;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.tongxun.atongmu.dialog.CommonDialog;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class CircleViedoActivity extends Activity implements View.OnClickListener,MediaRecorder.OnErrorListener {
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private ProgressBar mProgressBar;
private Button shoot_button;
private ImageView circle_light_btn;
private ImageView circle_change_camera_btn;
private TextView circle_camera_time;
private MediaRecorder mMediaRecorder;
private Camera mCamera;
private Timer mTimer;//
private OnRecordFinishListener mOnRecordFinishListener;//
private int mWidth;//
private int mHeight;//
private boolean isOpenCamera;//
private int mRecordMaxTime;//
private int mTimeCount;//
private int mNumberOfCameras=0;//
Bitmap bitmap;//
private int screenWidth;
public static File mVecordFile = null;//
private boolean isOpenFlash=false;
private boolean isBackCamera=true;
private int mbackCamera;
private int mfrontCamera;
private CommonDialog commonDialog;
private static final int MOVICE_SUCCESS=1000;//
private static final int MOVICE_FILE=1001;//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_super_video);
init_datas();
init_view();
set_datas();
init_event();
}
private void init_datas() {
isOpenCamera=true;//
mRecordMaxTime=10;//
//
Camera.CameraInfo cameraInfo=new Camera.CameraInfo();
mNumberOfCameras=Camera.getNumberOfCameras();
for(int camidx=0;camidx<mNumberOfCameras;camidx++){
Camera.getCameraInfo(camidx, cameraInfo);
if(cameraInfo.facing==Camera.CameraInfo.CAMERA_FACING_BACK){
mbackCamera=camidx;
}else if(cameraInfo.facing==Camera.CameraInfo.CAMERA_FACING_FRONT){
mfrontCamera=camidx;
}
}
}
private void init_view() {
mWidth=640;
mHeight=480;
//
screenWidth = getWindowManager().getDefaultDisplay().getWidth();
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);//
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);//
shoot_button = (Button) findViewById(R.id.shoot_button);//
circle_camera_time= (TextView) findViewById(R.id.circle_camera_time);
circle_change_camera_btn= (ImageView) findViewById(R.id.circle_change_camera_btn);//
circle_light_btn= (ImageView) findViewById(R.id.circle_light_btn);//
ViewGroup.LayoutParams params=mSurfaceView.getLayoutParams();
params.height=(screenWidth*4)/3;
params.width=screenWidth;
mSurfaceView.setLayoutParams(params);
top_model2_left_img= (ImageView)findViewById(R.id.top_model2_left_img);
top_model2_left_img.setOnClickListener(this);
top_model2_right_img= (ImageView)findViewById(R.id.top_model2_right_img);
top_model2_right_img.setVisibility(View.INVISIBLE);
top_model2_txt= (TextView)findViewById(R.id.top_model2_txt);
top_model2_txt.setText(" ");
}
private void set_datas() {
mSurfaceHolder = mSurfaceView.getHolder();
mProgressBar.setMax(mRecordMaxTime);//
mSurfaceHolder.setKeepScreenOn(true);//
mSurfaceHolder.addCallback(new CustomCallBack());
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
circle_camera_time.setText("");
}
private void init_event() {
circle_light_btn.setOnClickListener(this);
circle_change_camera_btn.setOnClickListener(this);
shoot_button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
record(new OnRecordFinishListener() {
@Override
public void onRecordFinish() {
//
handler.sendEmptyMessage(MOVICE_SUCCESS);
}
});
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (mTimeCount > 1 && mTimeCount<10) { // up
//
handler.sendEmptyMessage(MOVICE_SUCCESS);
} else if(mTimeCount<=1) {
//
if (getmVecordFile() != null) {
getmVecordFile().delete();
}
handler.sendEmptyMessage(MOVICE_FILE);
}
}
return true;
}
});
}
@Override
protected void onResume() {
super.onResume();
if(mCamera!=null){
freeCameraResource();
}
try {
initCamera();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// mRecorderView.stop();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//
stopRecord();
switch (msg.what){
case MOVICE_SUCCESS:
String msgs = " ?";
commonDialog = new CommonDialog(CircleViedoActivity.this, new CommonDialog.GoCommonDialog() {
@Override
public void go() {
finishActivity();
commonDialog.dismiss();
}
@Override
public void cancel() {
//
if (getmVecordFile() != null) {
getmVecordFile().delete();
}
commonDialog.dismiss();
}
}, msgs, " ", " ");
commonDialog.show();
break;
case MOVICE_FILE:
Toast.makeText(CircleViedoActivity.this, " ", Toast.LENGTH_SHORT).show();
break;
}
}
};
private void finishActivity() {
stop();
Bitmap bitmap = null;
if (getmVecordFile() != null) {
// File
File mfile = getmVecordFile();
bitmap = getVideoThumbnail(mfile.toString());
}
/**
* Android ,
*/
// VideoPlayerActivity.startActivity(this, mRecorderView.getVecordFile().toString());
Intent intent = new Intent();
intent.putExtra("bitmap",bitmap);
setResult(RESULT_OK,intent);
finish();
}
@Override
public void onError(MediaRecorder mr, int what, int extra) {
try {
if (mr != null)
mr.reset();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.circle_light_btn:
//
if(isOpenFlash){
isOpenFlash=false;
circle_light_btn.setImageResource(R.drawable.camera_light);
}else {
isOpenFlash=true;
circle_light_btn.setImageResource(R.drawable.camera_no_light);
}
try {
initCamera();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.circle_change_camera_btn:
if(isBackCamera){
isBackCamera=false;
}else {
isBackCamera=true;
}
try {
initCamera();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.top_model2_left_img:
stop();
finish();
break;
}
}
private class CustomCallBack implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!isOpenCamera)
return;
try {
initCamera();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
/**
*
*/
private void initCamera() throws IOException {
if (mCamera != null) {
freeCameraResource();
}
try {
if(isBackCamera){
mCamera = Camera.open(mbackCamera);//
setCameraParams(isOpenFlash);
}else {
mCamera=Camera.open(mfrontCamera);//
}
} catch (Exception e) {
e.printStackTrace();
freeCameraResource();
}
if (mCamera == null)
return;
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
mCamera.unlock();
}
/**
*
*/
private void setCameraParams(Boolean isOpenFlash) {
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
//
List<Camera.Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
params.set("orientation", "portrait");//
params.setPreviewSize(mWidth, mHeight);// 640*480
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//
if(isBackCamera){
if(isOpenFlash){
//
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
}else {
//
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
}else {
}
mCamera.setParameters(params);
}
}
/**
*
*/
private void freeCameraResource() {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.lock();
mCamera.release();
mCamera = null;
}
}
private void createRecordDir() {
File sampleDir = new File(Environment.getExternalStorageDirectory() + File.separator + "ATOMImg/video/");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
File vecordDir = sampleDir;
//
try {
mVecordFile = File.createTempFile("recording", ".mp4", vecordDir);//mp4
} catch (IOException e) {
}
}
/**
*
*/
private void initRecord() throws IOException {
mMediaRecorder = new MediaRecorder();
mMediaRecorder.reset();
if (mCamera != null)
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setOnErrorListener(this);
mMediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//
mMediaRecorder.setVideoSize(mWidth, mHeight);// :
// mMediaRecorder.setVideoFrameRate(16);// ,
mMediaRecorder.setVideoEncodingBitRate(1 * 1024 * 1024);// ,
if(isBackCamera) {
mMediaRecorder.setOrientationHint(90);// 90 ,
}else {
mMediaRecorder.setOrientationHint(270);
}mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//
----------
/**
IOS Android IOS Android H264 OPPO
*/
----------
// mediaRecorder.setMaxDuration(Constant.MAXVEDIOTIME * 1000);
mMediaRecorder.setOutputFile(mVecordFile.getAbsolutePath());
mMediaRecorder.prepare();
try {
mMediaRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*/
public interface OnRecordFinishListener {
public void onRecordFinish();
}
/**
*
* @param onRecordFinishListener
*/
public void record(final OnRecordFinishListener onRecordFinishListener) {
this.mOnRecordFinishListener = onRecordFinishListener;
createRecordDir();//
try {
if (!isOpenCamera)// ,
initCamera();//
initRecord();//
mTimeCount = 0;//
mTimer = new Timer();//
mTimer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
mTimeCount++;
mProgressBar.setProgress(mTimeCount);//
// handler.sendEmptyMessage(TIME_CHANGW);
runOnUiThread(new Runnable() {
@Override
public void run() {
circle_camera_time.setText(mTimeCount + "″");
}
});
if (mTimeCount == mRecordMaxTime) {// ,
//
if (mOnRecordFinishListener != null)
mOnRecordFinishListener.onRecordFinish();
}
}
}, 0, 1000);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
*/
public void stop() {
stopRecord();
releaseRecord();
freeCameraResource();
}
/**
*
*/
public void stopRecord() {
mProgressBar.setProgress(0);
circle_camera_time.setText("");
if (mTimer != null)
mTimer.cancel();
if (mMediaRecorder != null) {
//
mMediaRecorder.setOnErrorListener(null);
mMediaRecorder.setPreviewDisplay(null);
try {
mMediaRecorder.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* @return
*/
public File getmVecordFile() {
return mVecordFile;
}
/**
*
*/
private void releaseRecord() {
if (mMediaRecorder != null) {
mMediaRecorder.setOnErrorListener(null);
try {
mMediaRecorder.release();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
mMediaRecorder = null;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
stop();
finish();
return false;
}else {
return super.onKeyDown(keyCode, event);
}
}
/**
*
* @param filePath
* @return
*/
public Bitmap getVideoThumbnail(String filePath) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(filePath);
bitmap = retriever.getFrameAtTime();
}
catch(IllegalArgumentException e) {
e.printStackTrace();
}
catch (RuntimeException e) {
e.printStackTrace();
}
finally {
try {
retriever.release();
}
catch (RuntimeException e) {
e.printStackTrace();
}
}
return bitmap;
}
@Override
protected void onDestroy() {
super.onDestroy();
if(bitmap!=null){
try {
bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
bitmap=null;
}
}
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.