首页 > 代码库 > 前置摄像头后台视频录制,即可以自动拍摄也可以手动干涉,实现完全控制

前置摄像头后台视频录制,即可以自动拍摄也可以手动干涉,实现完全控制

package com.example.recorddemo;

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.main);
		// 初始化控件
		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()");
	}
	

}


录制 视频后台线程:

package com.example.recorddemo;

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.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() {
		
		mediarecorder = new MediaRecorder();// 创建mediarecorder对象
		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) {  
                    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(0);// 解决竖屏的时候,摄像头旋转90度的问题
		Camera.Parameters params=mCamera.getParameters();
		params.setPictureSize(320, 240);// 640x480,320x240,176x144,160x120
		mCamera.setParameters(params);

		// 解锁camera
		mCamera.unlock();
		mediarecorder.setCamera(mCamera);

		// 设置录制视频源为Camera(相机)
		mediarecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
		mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

		// 设置录制文件质量,格式,分辨率之类,这个全部包括了
		mediarecorder.setProfile(CamcorderProfile .get(CamcorderProfile.QUALITY_LOW));

		mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
		// 设置视频文件输出的路径
		mediarecorder.setOutputFile("/sdcard/sForm.3gp");
		mediarecorder.setVideoFrameRate(10);
		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()");
		if (mediarecorder != null) {
			// 停止录制
			mediarecorder.stop();
			// 释放资源
			mediarecorder.release();
			mediarecorder = null;

			if (mCamera != null) {
				mCamera.release();
				mCamera = null;
			}
		}
	}

	/**
	 * 定时器
	 * 
	 * @author bcaiw
	 * 
	 */
	class TimerThread extends TimerTask {

		/**
		 * 停止录像
		 */
		@Override
		public void run() {
			stopRecord();
			this.cancel();
		}
	}

}


main.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>

AndroidMaifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.recorddemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <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="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.recorddemo.RecordDemoActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

参考:http://wangb233.blog.163.com/blog/static/3710622920127285019645/

http://blog.csdn.net/gf771115/article/details/19438409



前置摄像头后台视频录制,即可以自动拍摄也可以手动干涉,实现完全控制