RecordThread.java
package com.example.zhaodebo.recorddemoactivity;
/**
* Created by zhaodebo on 17/3/23.
*/
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
@SuppressLint("NewApi")
public class RecordThread extends Thread {
private MediaRecorder mediarecorder;// 录制视频的类
private SurfaceHolder surfaceHolder;
private long recordTime;
private SurfaceView surfaceview;// 显示视频的控件
public Camera mCamera;
public RecordThread(long recordTime, SurfaceView surfaceview,
SurfaceHolder surfaceHolder) {
this.recordTime = recordTime;
this.surfaceview = surfaceview;
this.surfaceHolder = surfaceHolder;
}
@Override
public void run() {
/**
* 开始录像
*/
startRecord();
/**
* 启动定时器,到规定时间recordTime后执行停止录像任务
*/
Timer timer = new Timer();
timer.schedule(new TimerThread(), recordTime);
}
/**
* 获取摄像头实例对象
*
* @return
*/
public Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
// 打开摄像头错误
Log.i("info", "打开摄像头错误");
}
return c;
}
/**
* 开始录像
*/
public void startRecord() {
mCamera = getCameraInstance();
//切换前后摄像头
int cameraCount = 0;
CameraInfo cameraInfo = new CameraInfo();
cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数
int cameraPosition=1;
for(int i = 0; i < cameraCount; i++) {
Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
if(cameraPosition == 1) {
//现在是后置,变更为前置
//代表摄像头的方位,CAMERA_FACING_FRONT前置 CAMERA_FACING_BACK后置
if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
if (mCamera!=null) {
mCamera.stopPreview();//停掉原来摄像头的预览
mCamera.release();//释放资源
mCamera = null;//取消原来摄像头
}
mCamera = Camera.open(i);//打开当前选中的摄像头 1代表前置摄像头
try {
mCamera.setPreviewDisplay(surfaceHolder);//通过surfaceview显示取景画面
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();//开始预览
cameraPosition = 0;
break;
}
} else {
//现在是前置, 变更为后置
if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位,CAMERA_FACING_FRONT前置 CAMERA_FACING_BACK后置
mCamera.stopPreview();//停掉原来摄像头的预览
mCamera.release();//释放资源
mCamera = null;//取消原来摄像头
mCamera = Camera.open(i);//打开当前选中的摄像头
try {
mCamera.setPreviewDisplay(surfaceHolder);//通过surfaceview显示取景画面
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();//开始预览
cameraPosition = 1;
break;
}
}
}
mCamera.setDisplayOrientation(90);// 解决竖屏的时候,摄像头旋转90度的问题
Camera.Parameters params=mCamera.getParameters();
params.setPictureSize(640,480);// 640x480,320x240,176x144,160x120
mCamera.setParameters(params);
mCamera.unlock(); // 解锁camera
//1st. Initial state // 第1步:解锁并将摄像头指向MediaRecorder
mediarecorder = new MediaRecorder();
mediarecorder.setCamera(mCamera);
//2st. Initialized state // 第2步:指定源
mediarecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
//3st. config
// 第3步:指定CamcorderProfile(需要API Level 8以上版本)
// mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
//如果使用CamcorderProfile做配置的话,就应该注释设置输出格式,音频编码,视频编码3条语句
// 第3步:设置输出格式和编码格式(针对低于API Level 8版本)
mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediarecorder.setOutputFile("/sdcard/FBVideo.3gp");
mediarecorder.setVideoSize(640,480);//设置视频分辨率,这里很重要,设置错start()报未知错误
// mediarecorder.setVideoFrameRate(24);//设置视频帧率 这个我把它去掉了,感觉没什么用
mediarecorder.setVideoEncodingBitRate(10*1024*1024);//在这里我提高了帧频率,然后就清晰了 ,解决了花屏、绿屏的问题
mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
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();
}
}
/**
* 停止录制
*/
public void stopRecord() {
System.out.print("stopRecord()");
surfaceview = null;
surfaceHolder = null;
if (mediarecorder != null) {
// 停止录制
mediarecorder.stop();
mediarecorder.reset();
// 释放资源
mediarecorder.release();
mediarecorder = null;
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}
/**
* 定时器
*
* @author bcaiw
*
*/
class TimerThread extends TimerTask {
/**
* 停止录像
*/
@Override
public void run() {
stopRecord();
this.cancel();
}
}
}
2、
RecordDemoActivity.java
package com.example.zhaodebo.recorddemoactivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class RecordDemoActivity extends Activity implements SurfaceHolder.Callback {
private SurfaceView surfaceview;// 视频预览控件
private LinearLayout lay; // 预揽控件的
private Button start; //
private Button stop; //
private SurfaceHolder surfaceHolder; // 和surfaceView相关的
private RecordThread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_demo);
// 初始化控件
init();
}
/**
* 初始化控件以及回调
*/
private void init() {
surfaceview = (SurfaceView) this.findViewById(R.id.surfaceview);
lay = (LinearLayout) this.findViewById(R.id.lay);
start = (Button) this.findViewById(R.id.start);
stop = (Button) this.findViewById(R.id.stop);
// lay.setVisibility(LinearLayout.INVISIBLE);
SurfaceHolder holder = this.surfaceview.getHolder();// 取得holder
holder.addCallback(this); // holder加入回调接口
// 设置setType
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (thread==null) {
thread = new RecordThread(10*60*1000, surfaceview, surfaceHolder);
thread.start();
}else {
Toast.makeText(RecordDemoActivity.this, "正在录制中……", Toast.LENGTH_SHORT).show();
}
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (thread!=null) {
thread.stopRecord();
thread=null;
}else {
Toast.makeText(RecordDemoActivity.this, "视频录制还没开始", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
// 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder
Log.i("SurfaceHolder", "surfaceChanged()");
surfaceHolder = holder;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.i("SurfaceHolder", Thread.currentThread().getName());
// 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder
surfaceHolder = holder;
// 录像线程,当然也可以在别的地方启动,但是一定要在onCreate方法执行完成以及surfaceHolder被赋值以后启动
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
Log.i("SurfaceHolder", "surfaceDestroyed()");
// surfaceDestroyed的时候同时对象设置为null
surfaceview = null;
surfaceHolder = null;
/*释放资源 mediarecorder mCamera 否则会后果很严重*/
if (thread!=null) {
thread.stopRecord();
thread=null;
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("RecordDemoActivity", "onResume()");
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("RecordDemoActivity", "onPause()");
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("RecordDemoActivity", "onDestroy()");
}
}
3、AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zhaodebo.recorddemoactivity">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".RecordDemoActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
4、xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="stop" />
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="start" />
</LinearLayout>
<LinearLayout
android:id="@+id/lay"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginBottom="20dp"
android:layout_weight="1" >
<SurfaceView
android:id="@+id/surfaceview"
android:layout_width="fill_parent"
android:layout_height="300dp" />
</LinearLayout>
</LinearLayout>
本文转自:http://lib.csdn.net/article/liveplay/40284