Android開發手記(31) 使用MediaRecorder錄音

來源:互聯網
上載者:User

標籤:

      使用Android手機的時候,有時我們會用到錄音功能,本文簡單的介紹了如何使用MediaRecorder通過手機內建麥克風進行錄音。

      首先,既然是錄音,我們需要錄音和寫外存的許可權:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.RECORD_AUDIO"/>

      然後,我們建立一個錄音的方法startRecord(),當我們單擊錄音按鈕時調用這個方法來進行錄音。錄音的過程為:

(1)確定錄音的檔案的存放位置

(2)執行個體化一個MediaRecorder對象,並設定其參數

(3)調用MediaRecorder.prepare()準備錄音

(4)調用MediaRecorder.start()開始錄音

    public void startRecord(){        if(mr == null){            File filePath = new File(Environment.getExternalStorageDirectory(), "myRecord");            File fileName = new File(filePath, System.currentTimeMillis() + ".amr");            try {                if (!filePath.exists()) {                    filePath.mkdirs();                }                if (!fileName.exists()) {                    fileName.createNewFile();                }            } catch(IOException e){                e.printStackTrace();            }            mr = new MediaRecorder();            mr.setAudioSource(MediaRecorder.AudioSource.MIC);      // 設定錄音的輸入源            mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB); // 設定輸出格式            mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB); // 設定編碼格式            mr.setOutputFile(fileName.getAbsolutePath());          // 設定輸出檔案名            try{                mr.prepare();                mr.start();                textView.setText("檔案名稱:"+fileName.getAbsolutePath());            } catch(IOException e){                e.printStackTrace();            }        }    }

      然後我們建立一個方法stopRecord()來停止錄音,調用MediaRecorder.stop()可以停止錄音,調用MediaRecorder.release()釋放錄音對象。然後將MediaRecorder指標置空以便下一次錄音可以執行個體化新的MediaRecorder對象。

    public void stopRecord(){        if(mr != null){            mr.stop();            mr.release();            mr = null;        }    }

      最後,在MainActivity中為按鈕添加單擊事件,並調用上述方法即可實現錄音。完整代碼如下:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.doodle.myapplication">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.RECORD_AUDIO"/></manifest>
import android.app.Activity;import android.media.MediaRecorder;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.io.File;import java.io.IOException;public class MainActivity extends Activity {    private Button button;    private TextView textView;    private boolean isStart = false;    private MediaRecorder mr = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button = (Button)findViewById(R.id.button);        textView = (TextView)findViewById(R.id.textView);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if(isStart){                    startRecord();                    button.setText("停止錄音");                    isStart = false;                }                else {                    stopRecord();                    button.setText("開始錄音");                    isStart = true;                }            }        });    }    public void startRecord(){        if(mr == null){            File filePath = new File(Environment.getExternalStorageDirectory(), "myRecord");            File fileName = new File(filePath, System.currentTimeMillis() + ".amr");            try {                if (!filePath.exists()) {                    filePath.mkdirs();                }                if (!fileName.exists()) {                    fileName.createNewFile();                }            } catch(IOException e){                e.printStackTrace();            }            mr = new MediaRecorder();            mr.setAudioSource(MediaRecorder.AudioSource.MIC);      // 設定錄音的輸入源            mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB); // 設定輸出格式            mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB); // 設定編碼格式            mr.setOutputFile(fileName.getAbsolutePath());          // 設定輸出檔案名            try{                mr.prepare();                mr.start();                textView.setText("檔案名稱:"+fileName.getAbsolutePath());            } catch(IOException e){                e.printStackTrace();            }        }    }    public void stopRecord(){        if(mr != null){            mr.stop();            mr.release();            mr = null;        }    }}

Android開發手記(31) 使用MediaRecorder錄音

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.