Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義錄像(一):MediaRecorder 加 SurfaceView 實現錄像功能

編輯:關於 Android 程式設計

引言

最近在做的項目需要用手機攝像頭做圖像實時識別,因此必須自己定製一個錄像功能。這個 Demo 實現了錄像、錄像文件的保存與查看,並在錄像過程中實時自動對焦(AutoFocus)。功能拆成兩篇來寫,這一篇講錄像的基本實現思路和幾個容易踩的坑,文末附 GitHub 源碼。

思路

Android 實現錄像主要依靠兩個類:MediaRecorder 和 SurfaceView。此外因為需要對攝像頭參數做設置,還要用到 Camera 類。三者分工是:

  • MediaRecorder:負責控制錄像的音視頻源、輸出格式與編碼器。
  • SurfaceView:作為 View 提供用戶界面,並在自身不同的生命週期裡執行對應的初始化和釋放操作。
  • Camera:負責攝像頭參數配置,最後通過 MediaRecorder 的 setCamera() 把 Camera 對象關聯進去。

一、布局

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <SurfaceView
        android:id="@+id/capture_surfaceview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="0.0dip"
            android:layout_height="fill_parent"
            android:layout_gravity="left"
            android:layout_weight="5.0">

            <TextView
                android:id="@+id/capture_textview_information"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:layout_margin="10.0dip"
                android:textColor="@color/red_overlay"
                android:textSize="15.0sp" />

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0.0dip"
            android:layout_height="fill_parent"
            android:layout_gravity="right"
            android:layout_weight="1.0"
            android:alpha="0.3"
            android:background="@color/white_overlay"
            android:padding="20.0dip">

            <ImageButton
                android:id="@+id/capture_imagebutton_setting"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:background="@drawable/settings"
                android:contentDescription="@string/imagedescription"
                android:tag="setting" />

            <ImageButton
                android:id="@+id/ib_stop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/rec_start"
                android:contentDescription="@string/imagedescription"
                android:tag="start" />

            <ImageButton
                android:id="@+id/capture_imagebutton_showfiles"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:background="@drawable/folder"
                android:contentDescription="@string/imagedescription"
                android:tag="showfiles" />

        </RelativeLayout>

    </LinearLayout>

</FrameLayout>

二、布局效果

三、核心代碼

package com.alanjet.videorecordertest;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.File;
import java.util.Calendar;

public class MainActivity extends Activity implements SurfaceHolder.Callback {

    private static final String TAG = "MainActivity";

    private SurfaceView mSurfaceview;
    private ImageButton mBtnStartStop;
    private ImageButton mBtnSet;
    private ImageButton mBtnShowFile;

    private boolean mStartedFlg = false;
    private MediaRecorder mRecorder;
    private SurfaceHolder mSurfaceHolder;
    private Camera myCamera;
    private Camera.Parameters myParameters;
    private boolean isView = false;

    /** 自動對焦回調 */
    private Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            Log.i(TAG, "AutoFocus: " + (success ? "success..." : "failure..."));
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initScreen();
        setContentView(R.layout.activity_main);

        mSurfaceview = (SurfaceView) findViewById(R.id.capture_surfaceview);
        mBtnStartStop = (ImageButton) findViewById(R.id.ib_stop);
        mBtnSet = (ImageButton) findViewById(R.id.capture_imagebutton_setting);
        mBtnShowFile = (ImageButton) findViewById(R.id.capture_imagebutton_showfiles);

        mBtnShowFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ShowVideoActivity.class));
                finish();
            }
        });

        mBtnSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "相機設置待開發~", Toast.LENGTH_SHORT).show();
            }
        });

        SurfaceHolder holder = mSurfaceview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    /** 用系統時間戳作為文件名,避免重名 */
    public static String getDate() {
        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);
        int month = ca.get(Calendar.MONTH);
        int day = ca.get(Calendar.DATE);
        int minute = ca.get(Calendar.MINUTE);
        int hour = ca.get(Calendar.HOUR);
        int second = ca.get(Calendar.SECOND);
        String date = "" + year + (month + 1) + day + hour + minute + second;
        Log.d(TAG, "date:" + date);
        return date;
    }

    /** 獲取 SD 卡路徑 */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
            return sdDir.toString();
        }
        return null;
    }

    /** 全屏橫屏初始化 */
    public void initScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 有 SurfaceView 的 Activity 需要半透明模式
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
    }

    /** 初始化 Camera */
    public void initCamera() {
        if (myCamera == null && !isView) {
            myCamera = Camera.open();
            Log.i(TAG, "camera.open");
        }
        if (myCamera != null && !isView) {
            try {
                myParameters = myCamera.getParameters();
                myParameters.setPreviewSize(1920, 1080);
                // 連續視頻對焦模式,是實現實時自動對焦的關鍵
                myParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                myCamera.setParameters(myParameters);
                myCamera.setPreviewDisplay(mSurfaceHolder);
                myCamera.startPreview();
                isView = true;
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "初始化相機錯誤",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mSurfaceHolder = holder;
        initCamera();

        mBtnStartStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mStartedFlg) {
                    if (mRecorder == null) {
                        mRecorder = new MediaRecorder();
                    }
                    try {
                        // 錄像前必須 unlock,否則 MediaRecorder 拿不到 Camera
                        myCamera.unlock();
                        mRecorder.setCamera(myCamera);

                        // 音視頻源必須在 setOutputFormat 之前設置
                        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

                        mRecorder.setProfile(
                                CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
                        mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

                        String path = getSDPath();
                        if (path != null) {
                            File dir = new File(path + "/VideoRecorderTest");
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            path = dir + "/" + getDate() + ".mp4";
                            mRecorder.setOutputFile(path);

                            mRecorder.prepare();
                            mRecorder.start();
                            mStartedFlg = true;
                            mBtnStartStop.setBackground(
                                    getDrawable(R.drawable.rec_stop));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if (mStartedFlg) {
                        try {
                            mRecorder.stop();
                            mRecorder.reset();
                            mBtnStartStop.setBackground(
                                    getDrawable(R.drawable.rec_start));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mStartedFlg = false;
                }
            }
        });
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // 對象置空,避免內存洩漏
        mSurfaceview = null;
        mSurfaceHolder = null;
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
    }
}

四、Manifest 權限配置

<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.MOUNT_UNMOUNT_FILESYSTEMS" />

五、幾個必須注意的點

  1. SurfaceView 的生命週期是整個錄像流程的骨架。 通過 SurfaceHolder holder = mSurfaceView.getHolder() 拿到 holder,再 holder.addCallback(this) 進入回調,然後重寫 surfaceCreated / surfaceChanged / surfaceDestroyed 三個方法,把相機初始化、录制控制、資源釋放分別放在合適的時機。
  2. 自動對焦的關鍵有兩處: 一是重寫 Camera.AutoFocusCallback 接口; 二是把 parameters 的對焦模式設為 Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,讓系統在錄像過程中持續對焦。
  3. MediaRecorder 的方法調用順序不能亂。 音視頻源(setAudioSource / setVideoSource)必須在 setOutputFormat 之前;而 setCamera 之後、prepare 之前要先對 Camera 執行 unlock(),否則會直接拋異常。
  4. 6.0 以上記得做動態權限申請。 本文示例基於早期版本,實際運行時相機、錄音、寫存儲三項權限都需要動態申請。

六、運行效果

七、Demo 源碼

https://github.com/alanjet/VideoRecorderTest.git


後記

下一篇《Android 自定義錄像(二)之錄像文件保存查看實現》近期發佈。

在實踐中求真知,在技術中尋快樂。這是自己在項目裡積累的一點心得,希望能幫到有需要的 Android 開發者。這也是我寫的第一篇 CSDN 博客,表達未必精準,很多地方也還稚嫩,歡迎在評論裡多指點、多交流。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved