============================首先看看官网上关于视频捕捉的介绍================================

Capturing videos

Video capture using the Android framework requires careful management of theCameraobject and coordination with theMediaRecorderclass. When recording video withCamera, you must manage theCamera.lock()andCamera.unlock()calls to allowMediaRecorderaccess to the camera hardware, in addition to theCamera.open()andCamera.release()calls.

Note:Starting with Android 4.0 (API level 14), theCamera.lock()andCamera.unlock()calls are managed for you automatically.

Unlike taking pictures with a device camera, capturing video requires a very particular call order. You must follow a specific order of execution to successfully prepare for and capture video with your application, as detailed below.

  1. Open Camera- Use theCamera.open()to get an instance of the camera object.
  2. Connect Preview- Prepare a live camera image preview by connecting aSurfaceViewto the camera usingCamera.setPreviewDisplay().
  3. Start Preview- CallCamera.startPreview()to begin displaying the live camera images.
  4. Start Recording Video- The following steps must be completedin orderto successfully record video:
    1. Unlock the Camera- Unlock the camera for use byMediaRecorderby callingCamera.unlock().
    2. Configure MediaRecorder- Call in the followingMediaRecordermethodsin this order. For more information, see theMediaRecorderreference documentation.
      1. setCamera()- Set the camera to be used for video capture, use your application's current instance ofCamera.
      2. setAudioSource()- Set the audio source, useMediaRecorder.AudioSource.CAMCORDER.
      3. setVideoSource()- Set the video source, useMediaRecorder.VideoSource.CAMERA.
      4. Set the video output format and encoding. For Android 2.2 (API Level 8) and higher, use theMediaRecorder.setProfilemethod, and get a profile instance usingCamcorderProfile.get(). For versions of Android prior to 2.2, you must set the video output format and encoding parameters:
        1. setOutputFormat()- Set the output format, specify the default setting orMediaRecorder.OutputFormat.MPEG_4.
        2. setAudioEncoder()- Set the sound encoding type, specify the default setting orMediaRecorder.AudioEncoder.AMR_NB.
        3. setVideoEncoder()- Set the video encoding type, specify the default setting orMediaRecorder.VideoEncoder.MPEG_4_SP.
      5. setOutputFile()- Set the output file, usegetOutputMediaFile(MEDIA_TYPE_VIDEO).toString()from the example method in theSaving Media Filessection.
      6. setPreviewDisplay()- Specify theSurfaceViewpreview layout element for your application. Use the same object you specified forConnect Preview.

      Caution:You must call theseMediaRecorderconfiguration methodsin this order, otherwise your application will encounter errors and the recording will fail.

    3. Prepare MediaRecorder- Prepare theMediaRecorderwith provided configuration settings by callingMediaRecorder.prepare().
    4. Start MediaRecorder- Start recording video by callingMediaRecorder.start().
  5. Stop Recording Video- Call the following methodsin order, to successfully complete a video recording:
    1. Stop MediaRecorder- Stop recording video by callingMediaRecorder.stop().
    2. Reset MediaRecorder- Optionally, remove the configuration settings from the recorder by callingMediaRecorder.reset().
    3. Release MediaRecorder- Release theMediaRecorderby callingMediaRecorder.release().
    4. Lock the Camera- Lock the camera so that futureMediaRecordersessions can use it by callingCamera.lock(). Starting with Android 4.0 (API level 14), this call is not required unless theMediaRecorder.prepare()call fails.
  6. Stop the Preview- When your activity has finished using the camera, stop the preview usingCamera.stopPreview().
  7. Release Camera- Release the camera so that other applications can use it by callingCamera.release().

Note:It is possible to useMediaRecorderwithout creating a camera preview first and skip the first few steps of this process. However, since users typically prefer to see a preview before starting a recording, that process is not discussed here.

Tip:If your application is typically used for recording video, setsetRecordingHint(boolean)totrueprior to starting your preview. This setting can help reduce the time it takes to start recording.


============================再看看官网上关于音频捕捉的介绍================================

Audio Capture

The Android multimedia framework includes support for capturing and encoding a variety of common audio formats, so that you can easily integrate audio into your applications. You can record audio using theMediaRecorderAPIs if supported by the device hardware.

This document shows you how to write an application that captures audio from a device microphone, save the audio and play it back.

Note:The Android Emulator does not have the ability to capture audio, but actual devices are likely to provide these capabilities.

Performing Audio Capture

Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple:

  1. Create a new instance ofandroid.media.MediaRecorder.
  2. Set the audio source usingMediaRecorder.setAudioSource(). You will probably want to useMediaRecorder.AudioSource.MIC.
  3. Set output file format usingMediaRecorder.setOutputFormat().
  4. Set output file name usingMediaRecorder.setOutputFile().
  5. Set the audio encoder usingMediaRecorder.setAudioEncoder().
  6. CallMediaRecorder.prepare()on the MediaRecorder instance.
  7. To start audio capture, callMediaRecorder.start().
  8. To stop audio capture, callMediaRecorder.stop().
  9. When you are done with the MediaRecorder instance, callMediaRecorder.release()on it. CallingMediaRecorder.release()is always recommended to free the resource immediately.


下面就看看该小例子的代码吧。

文件1.该应用的布局文件,res/layout/main.xml

<!-- 帧布局 --><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:layout_height="fill_parent"><!-- 用来展示画面 --><SurfaceView android:id="@+id/surfaceView"android:layout_width="fill_parent" android:layout_height="fill_parent" /><!-- 相对布局,该界面默认不显示出来,当触摸屏幕时候显示出来 --><RelativeLayout android:layout_width="fill_parent"android:layout_height="fill_parent" android:visibility="gone"android:id="@+id/buttonlayout"><!-- 刻录按钮 --><Button android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_alignParentRight="true"android:layout_alignParentBottom="true" android:layout_marginRight="10dp"android:text="@string/recoderbutton" android:onClick="recoder"android:id="@+id/recoderbutton" /><!-- 停止按钮 --><Button android:layout_width="wrap_content"android:layout_height="wrap_content" android:layout_toLeftOf="@id/recoderbutton"android:layout_alignTop="@id/recoderbutton" android:layout_marginRight="30dp"android:text="@string/stopbutton" android:onClick="stop"android:id="@+id/stopbutton" android:enabled="false"/></RelativeLayout></FrameLayout>

文件2:布局文件所用到的资源文件,res/values/string.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="hello">Hello World, RecoderActivity!</string>    <string name="app_name">视频刻录小例子</string>    <string name="recoderbutton">刻录</string>    <string name="stopbutton">停止</string>    <string name="noSDcard">检测到手机没有存储卡!请插入手机存储卡再开启本应用</string>    <string name="maxDuration">已经达到最长录制时间</string></resources>

文件3:该应用的主程序,RecoderActivity.java

package cn.oyp.recoder;import java.io.File;import android.app.Activity;import android.content.pm.ActivityInfo;import android.media.MediaRecorder;import android.media.MediaRecorder.OnInfoListener;import android.os.Bundle;import android.os.Environment;import android.view.MotionEvent;import android.view.SurfaceHolder;import android.view.SurfaceView;import android.view.View;import android.view.ViewGroup;import android.view.Window;import android.view.WindowManager;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.Toast;public class RecoderActivity extends Activity {// 用来显示图片private SurfaceView surfaceView;// 刻录和停止按钮布局private RelativeLayout buttonlayout;// 刻录按钮private Button recoderbutton;// 停止按钮private Button stopbutton;// 媒体刻录对象private MediaRecorder mediaRecorder;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 窗口特效为无标题requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置窗口全屏getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设定屏幕显示为横向setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);setContentView(R.layout.main);buttonlayout = (RelativeLayout) this.findViewById(R.id.buttonlayout);recoderbutton = (Button) this.findViewById(R.id.recoderbutton);stopbutton = (Button) this.findViewById(R.id.stopbutton);surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);// 获取的画面直接输出到屏幕上surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// 画面分辨率surfaceView.getHolder().setFixedSize(176, 144);// 保持屏幕高亮surfaceView.getHolder().setKeepScreenOn(true);}// 点击刻录按钮处理方法public void recoder(View v) {try {// 判断是否存在SD卡if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 将刻录的视频保存到SD卡中File videoFile = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".3gp");mediaRecorder = new MediaRecorder();// 设置声音采集来源于麦克风mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置视频采集来源于摄像头mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);// 设置输出格式为3gpmediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);// 设置视频尺寸mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());// 设置每秒钟捕捉画面个数为5帧mediaRecorder.setVideoFrameRate(5);// 设置声音编码mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);// 设置视频编码mediaRecorder.setAudioEncoder(MediaRecorder.VideoEncoder.H264);// 设置视频的最大持续时间mediaRecorder.setMaxDuration(10000);mediaRecorder.setOnInfoListener(new OnInfoListener() {@Overridepublic void onInfo(MediaRecorder mr, int what, int extra) {if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {Toast.makeText(getApplicationContext(),R.string.maxDuration, Toast.LENGTH_LONG).show();if (mediaRecorder != null) {mediaRecorder.stop();mediaRecorder.release();mediaRecorder = null;}}}});// 设置刻录的视频保存路径mediaRecorder.setOutputFile(videoFile.getAbsolutePath());// 设置预览显示mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());// 预期准备mediaRecorder.prepare();// 开始刻录mediaRecorder.start();} else {Toast.makeText(getApplicationContext(), R.string.noSDcard,Toast.LENGTH_LONG).show();}} catch (Exception e) {e.printStackTrace();}// 刻录按钮不可点击recoderbutton.setEnabled(false);// 停止按钮可点击stopbutton.setEnabled(true);}// 点击停止按钮处理方法public void stop(View v) {// 停止刻录,并释放资源if (mediaRecorder != null) {mediaRecorder.stop();mediaRecorder.release();mediaRecorder = null;}// 刻录按钮可点击recoderbutton.setEnabled(true);// 停止按钮不可点击stopbutton.setEnabled(false);}/** 当触摸屏幕的时候,将对焦和拍照按钮布局显示出来 */@Overridepublic boolean onTouchEvent(MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_DOWN) {buttonlayout.setVisibility(ViewGroup.VISIBLE);return true;}return super.onTouchEvent(event);}}

文件4:该应用的描述文件 ,AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="cn.oyp.recoder" android:versionCode="1" android:versionName="1.0"><uses-sdk android:minSdkVersion="8" /><!-- 摄像头权限 --><uses-permission android:name="android.permission.CAMERA" /><!-- 录制音频权限 --><uses-permission android:name="android.permission.RECORD_AUDIO"/><!-- 在SD卡中创建和删除文件权限 --><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /><!-- 往SD卡中写入数据的权限 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><application android:icon="@drawable/icon" android:label="@string/app_name"><activity android:name=".RecoderActivity" android:label="@string/app_name"android:screenOrientation="landscape"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

=================================================================================================

作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!

转载请保留原文地址:http://blog.csdn.net/ouyang_peng

==================================================================================================

更多相关文章

  1. Android--利用selector设置Button
  2. Android(安卓)设置全屏显示
  3. Android底部导航栏实现(三)之TextView+LinearLayout
  4. Android中设置关键字高亮的方法
  5. Android回调——Android模块化编程
  6. Android修行之路——Dialog
  7. Android(安卓)按钮添加单击事件
  8. AndroidMainifest标签使用说明3——<activity-alias>
  9. Android官方入门文档[6]添加Action按钮

随机推荐

  1. PHP调用存储过程失败(没有执行到)--mysql_e
  2. 在php中检测浏览器,版本和平台的可靠方法
  3. 如何知道php zip扩展程序是否已安装?如何
  4. 从mysql中选择加密密码
  5. 《PHP高级知识进阶》系列技术文章整理收
  6. [CI]CodeIgniter视图 & 模型 & 控制器
  7. 不使用PHP框架的原因?
  8. 如何在没有小部件工厂的情况下在Yii2中设
  9. Zend Framework 2:活动菜单项。
  10. 如何使用Javascript ajax发送网址? [重复]