object and coordination with the class. When recording video with , you must manage the and calls to allow access to the camera hardware, in addition to the and calls.
Note: Starting with Android 4.0 (API level 14), the and calls are managed for you automatically.
Open Camera - Use the to get an instance of the camera object.- Connect Preview - Prepare a live camera image preview by connecting a
to the camera using.
Start Preview - Call to begin displaying the live camera images.
Start Recording Video - The following steps must be completed in order to successfully record video:
Unlock the Camera - Unlock the camera for use by
by calling .- Configure MediaRecorder - Call in the following
methods in this order. For more information, see the reference documentation.
- Set the camera to be used for video capture, use your application's current instance of
.- - Set the audio source, use
.
- Set the video source, use .
method, and get a profile instance using . For versions of Android prior to 2.2, you must set the video output format and encoding parameters:
- Set the output format, specify the default setting or
.- - Set the sound encoding type, specify the default setting or
.
- Set the video encoding type, specify the default setting or.
- Set the output file, use from the example method in the Saving Media Files section.
- Specify the preview layout element for your application. Use the same object you specified for Connect Preview.
Caution: You must call these configuration methods in this order, otherwise your application will encounter errors and the recording will fail.
Prepare MediaRecorder - Prepare the with provided configuration settings by calling.
Start MediaRecorder - Start recording video by calling .
Stop Recording Video - Call the following methods in order, to successfully complete a video recording:
Stop MediaRecorder - Stop recording video by calling
.- Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling
.
Release MediaRecorder - Release the by calling .
Lock the Camera - Lock the camera so that future sessions can use it by calling. Starting with Android 4.0 (API level 14), this call is not required unless the call fails.
Stop the Preview - When your activity has finished using the camera, stop the preview using.
Release Camera - Release the camera so that other applications can use it by calling .
Note: It is possible to use without 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, set to prior to starting your preview. This setting can help reduce the time it takes to start recording.
APIs if supported by the device hardware.
Note: The Android Emulator does not have the ability to capture audio, but actual devices are likely to provide these capabilities.
.- . You will probably want to use
.
.
.
.
on the MediaRecorder instance.
.
.
on it. Calling is always recommended to free the resource immediately.
<!-- 幀布局 --><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>
<?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>
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);}}
<?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>