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

Android錄音功能實作教學:按住說話鬆開停止

編輯:關於 Android 程式設計

語音訊息已是現代通訊App的標配功能。本文將以實例形式,詳細示範如何在Android中實作錄音功能,模擬微信「按住說話、鬆開停止」的操作體驗,分享給大家參考。

首先是XML佈局檔,這裡只有一個「TALK」按鈕:

 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/btn_talk" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:enabled="false" android:text="TALK" android:textSize="30dp" android:text /> </LinearLayout> 

運行效果如下圖:

在 MainActivity 中定義按鈕的觸摸監聽器:按下時開始錄音,鬆開時停止錄音:

 // 獲得控件 public void get_con(){ btn_talk = (Button)findViewById(R.id.btn_talk); btn_talk.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_DOWN){ // 開始錄音 start_record(); } else if (e.getAction() == MotionEvent.ACTION_UP){ // 停止錄音 stop_record(); } return false; } }); } 

開始錄音的方法使用 android.media.MediaRecorder。首先判斷SD卡是否存在,若存在則依當前時間建立一個錄音檔並存到指定目錄,再透過 MediaRecorder 開始錄音:

 // 開始錄音 public void start_record(){ if (!Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){ show_status("SD卡不存在,請插入SD卡!"); } else{ try { // 獲取當前時間 cur_date = new Date(System.currentTimeMillis()); str_file = formatter.format(cur_date); // 創建保存錄音的音頻文件 send_sound_file = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/talk/send"); // 如果目錄不存在 if (!send_sound_file.exists()){ send_sound_file.mkdirs(); } send_sound_file = new File(Environment.getExternalStorageDirectory().getCanonicalFile() + "/talk/send/" + str_file + ".amr"); recorder = new MediaRecorder(); // 設置錄音的聲音來源 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 設置錄制的聲音的輸出格式(必須在設置聲音編碼格式之前設置) recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // 設置聲音編碼的格式 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(send_sound_file.getAbsolutePath()); recorder.prepare(); // 開始錄音 recorder.start(); } catch (Exception e) { show_status(e.toString()); } } } 

停止錄音的方法則相對簡單,停止錄音並釋放資源即可:

 // 停止錄音 public void stop_record(){ if (send_sound_file != null && send_sound_file.exists()) { ses_id = ses_id + 1; // 停止錄音 recorder.stop(); // 釋放資源 recorder.release(); recorder = null; } super.onDestroy(); } 

這裡的關鍵在於 MediaRecorder 的設定順序:必須先設定輸出路徑與編碼格式,最後才能呼叫 prepare() 與 start()。經測試,錄製的 3gp/AMR 檔案可以正常播放。掌握這套流程,你就能為App加上完整的語音錄製功能。

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