Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

從零開始學 Android:用 MediaRecorder 錄製音訊

編輯:Android 技術基礎

用 MediaRecorder 完成錄音

Android 的 MediaRecorder 類別可以相對簡單地完成音訊錄製。不過要注意,模擬器對錄音支援有限,實際測試建議使用真機。

錄音前的九個步驟

  1. 建立 MediaRecorder 物件。
  2. 設定音訊來源為麥克風。
  3. 設定輸出格式。
  4. 設定輸出檔案路徑。
  5. 設定音訊編碼器。
  6. 呼叫 prepare()。
  7. 呼叫 start() 開始錄音。
  8. 停止時呼叫 stop()。
  9. 最後呼叫 release() 釋放資源。

介面設計

先將 record.png 與 stop.png 複製到 res/drawable-hdpi。

activity_main.xml 可放入兩個 ImageButton,分別代表開始錄音與停止錄音。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageButton
        android:id="@+id/record"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/record" />

    <ImageButton
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/stop" />
</LinearLayout>

程式實作

在 MainActivity 中,先檢查外部儲存是否可用,再建立檔案路徑。按下錄音鍵時,設定 MIC、THREE_GPP、AMR_NB,然後 prepare 與 start。

mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(path);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.prepare();
mRecorder.start();

停止錄音時,則要停止並釋放資源。

mRecorder.stop();
mRecorder.release();
mRecorder = null;

執行結果

點擊錄音按鈕後,系統會開始收音,停止後會產生 3gp 格式的音訊檔。


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