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

Android 錄音實作:MediaRecorder 搭配 MediaPlayer 完整流程

編輯:Android 開發實例

幾乎每支 Android 手機都內建麥克風,錄下聲音後存檔或播放都不是難事。做法有好幾種,最常見的是 MediaRecorder 類別;錄完之後再用 MediaPlayer 播放即可。本文用一個「開始、停止、播放」三顆按鈕的小程式把整個流程跑通。

MediaRecorder 的基本用法

先建立物件:

 MediaRecorder myAudioRecorder = new MediaRecorder();

接著依序設定音訊來源、輸出格式、編碼器與輸出檔案路徑。這四個設定的順序不能任意調換,否則會在 prepare() 時出錯:

 myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
 myAudioRecorder.setOutputFile(outputFile);

設定完成後,用 prepare() 準備、start() 開始錄製:

 myAudioRecorder.prepare();
 myAudioRecorder.start();

MediaRecorder 其餘常用的方法:

setAudioSource():指定要錄製的音訊來源。
setVideoSource():指定要錄製的影片來源。
setOutputFormat():指定輸出的容器格式。
setAudioEncoder():指定音訊編碼器。
setOutputFile():指定錄製結果的存放路徑。
stop():停止錄製。
release():釋放 MediaRecorder 實例,不再使用時務必呼叫。

實作步驟

這個範例結合 MediaRecorder 錄音與 MediaPlayer 播放。錄音與播放都牽涉到硬體資源,建議直接在實機上測試。準備工作包含建立專案、在 MainActivity 加入錄音程式碼、配置 activity_main.xml 的三顆按鈕、補上 string.xml 字串,以及在 AndroidManifest.xml 加入必要權限。

MainActivity.java

值得注意的細節是 stop() 之後一定要 release() 並把參照設為 null,否則下一次錄音會因為資源未釋放而失敗;同時要記得切換按鈕的啟用狀態,避免使用者在不恰當的時機按下停止。

 package com.example.audiocapture;
 import java.io.File;
 import java.io.IOException;
 import android.media.MediaPlayer;
 import android.media.MediaRecorder;
 import android.os.Bundle;
 import android.os.Environment;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;
 import android.widget.Button;
 import android.widget.Toast;

 public class MainActivity extends Activity {
 private MediaRecorder myAudioRecorder;
 private String outputFile = null;
 private Button start, stop, play;
 @Override protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 start = (Button)findViewById(R.id.button1);
 stop = (Button)findViewById(R.id.button2);
 play = (Button)findViewById(R.id.button3);
 stop.setEnabled(false);
 play.setEnabled(false);
 outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.3gp";
 myAudioRecorder = new MediaRecorder();
 myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
 myAudioRecorder.setOutputFile(outputFile);
 }
 public void start(View view){
 try {
 myAudioRecorder.prepare();
 myAudioRecorder.start();
 } catch (IllegalStateException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 start.setEnabled(false);
 stop.setEnabled(true);
 Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
 }
 public void stop(View view){
 myAudioRecorder.stop();
 myAudioRecorder.release();
 myAudioRecorder = null;
 stop.setEnabled(false);
 play.setEnabled(true);
 Toast.makeText(getApplicationContext(), "Audio recorded successfully", Toast.LENGTH_LONG).show();
 }
 @Override public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(R.menu.main, menu);
 return true;
 }
 public void play(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException{
 MediaPlayer m = new MediaPlayer();
 m.setDataSource(outputFile);
 m.prepare();
 m.start();
 Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
 }
 }

activity_main.xml

三顆按鈕分別用 android:onClick 對應到 Java 中的同名方法,版面以 ImageView 當作視覺重點:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
 xmlns:tools="https://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 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" >
 <TextView android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentRight="true"
 android:layout_alignParentTop="true"
 android:layout_marginTop="32dp"
 android:text="@string/Recording"
 android:textAppearance="?android:attr/textAppearanceMedium" />
 <ImageView android:id="@+id/imageView1"
 android:layout_width="100dp"
 android:layout_height="100dp"
 android:layout_below="@+id/textView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="37dp"
 android:scaleType="fitXY"
 android:src="@android:drawable/presence_audio_online" />
 <Button android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/imageView1"
 android:layout_marginTop="67dp"
 android:layout_toLeftOf="@+id/imageView1"
 android:onClick="start"
 android:text="@string/start" />
 <Button android:id="@+id/button2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignBaseline="@+id/button1"
 android:layout_alignBottom="@+id/button1"
 android:layout_alignRight="@+id/textView1"
 android:layout_marginRight="40dp"
 android:onClick="stop"
 android:text="@string/stop" />
 <Button android:id="@+id/button3"
 style="?android:attr/buttonStyleSmall"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/button2"
 android:layout_centerHorizontal="true"
 android:onClick="play"
 android:text="@string/play" />
 </RelativeLayout>

字串與權限

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
 <string name="app_name">AudioCapture</string>
 <string name="action_settings">Settings</string>
 <string name="hello_world">Hello world!</string>
 <string name="Recording">Android Audio Recording Application</string>
 <string name="start">start</string>
 <string name="stop">stop</string>
 <string name="play">play</string>
 </resources>

錄音需要 RECORD_AUDIO,寫檔需要 WRITE_EXTERNAL_STORAGE,兩者缺一不可:

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="https://schemas.android.com/apk/res/android"
 package="com.yiibai.audiocapture"
 android:versionCode="1"
 android:versionName="1.0" >
 <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.RECORD_AUDIO" />
 <application android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity android:name="com.yiibai.audiocapture.MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 </application>
 </manifest>

執行結果

選擇要執行的裝置:

App 啟動畫面,此時「停止」與「播放」是停用狀態:

按下「開始」,程式進入錄音狀態:

按下「停止」,錄音檔會存進外部儲存空間:

按下「播放」,剛錄好的聲音就會從裝置喇叭放出來:

實務上有幾點值得留意:Android 6.0 以後的執行期權限需要動態向使用者請求,不能只寫在 Manifest 裡;錄音格式若要在舊裝置或第三方服務間通用,AMR 未必是最佳選擇,AAC 或 WAV 相容性通常更好;另外別忘了在 Activity 的 onDestroy 或 onPause 中呼叫 release(),否則麥克風會被佔住,其他 App 就錄不了音。

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