我的Android進階之旅------>Android視頻錄製小例子

來源:互聯網
上載者:User


 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.
  1. Connect Preview - Prepare a live camera image preview by connecting a  to the camera using.
  2. Start Preview - Call  to begin displaying the live camera images.
  3. 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 .
    1. 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 .
      1.  - Set the audio source, use .
      2.  - Set the video source, use .
      3.  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 .
        1.  - Set the sound encoding type, specify the default setting or.
        2.  - Set the video encoding type, specify the default setting or.
      4.  - Set the output file, use  from the example method in the Saving Media Files section.
      5.  - 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.

    2. Prepare MediaRecorder - Prepare the  with provided configuration settings by calling.
    3. Start MediaRecorder - Start recording video by calling .
  4. Stop Recording Video - Call the following methods in order, to successfully complete a video recording:
      Stop MediaRecorder - Stop recording video by calling  .
    1. Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling.
    2. Release MediaRecorder - Release the  by calling .
    3. 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.
  5. Stop the Preview - When your activity has finished using the camera, stop the preview using.
  6. 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.

    .
  1. . You will probably want to use.
  2. .
  3. .
  4. .
  5.  on the MediaRecorder instance.
  6. .
  7. .
  8.  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>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.