有四個按鈕,分別是「錄音」、「中止」、「播放」、「刪除」。如圖1所示。
圖1:錄音機的界面
MediaRecorder的生命週期
MediaRecorder能夠用來錄製音頻或視頻。它具備如下幾個狀態:
Initial:初始狀態,在設定視頻源或者音頻源以後將轉換爲Initialized狀態。
Initialized:已初始化狀態,能夠經過設置輸出格式轉換爲DataSourceConfigured狀態,或者經過從新啓動轉換成Initial狀態。java
· 設置錄音來源 :android
· iMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);app
· 設置輸出格式:ide
· iMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);工具
· 設置編碼方式this
· iMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);編碼
· 設置輸出文件spa
· iMediaRecorder.setOutputFile(PATH_NAME);code
· 讓MediaRecorder對象處於就緒狀態orm
· iMediaRecorder.prepare();
· 開始錄音
· iMediaRecorder.start();
· 中止錄音,一旦中止則必須重新配置MediaRecorder對象才能再次開始錄音。
· iMediaRecorder.stop();
· 重新啓動MediaRecorder對象讓它處於空閒狀態。
· iMediaRecorder.reset();
· 釋放和MediaRecorder對向相關的全部資源。
· iMediaRecorder.release();
package com.ophone.iRecorder;
//這裏爲了節省篇幅,忽略了import項
public class ActivityMain extends Activity {
private ImageButton iRecordButton;
private ImageButton iStopButton;
private ImageButton iPlayButton;
private ImageButton iDeleteButton;
private ListView iListView;
private String iTempFileNameString = "iRecorder_";
private File iRecAudioFile;
private File iRecAudioDir;
private File iPlayFile;
private MediaRecorder iMediaRecorder;
private ArrayList<String> iRecordFiles;
private ArrayAdapter<String> iAdapter;
private TextView iTextView;
private boolean isSDCardExit;
private boolean isStopRecord;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iRecordButton = (ImageButton) findViewById(R.id.ImageButton01);
iStopButton = (ImageButton) findViewById(R.id.ImageButton02);
iPlayButton = (ImageButton) findViewById(R.id.ImageButton03);
iDeleteButton = (ImageButton) findViewById(R.id.ImageButton04);
iListView = (ListView) findViewById(R.id.ListView01);
iTextView = (TextView) findViewById(R.id.TextView01);
/* 初始後三個按鈕不可用 */
iStopButton.setEnabled(false);
iPlayButton.setEnabled(false);
iDeleteButton.setEnabled(false);
須要判斷SD卡是不是插入狀態,以保證咱們能夠長時間的進行錄音。若是存在則取得SD卡路徑做爲錄音的文件位置。而後取得SD卡中的.amr文件。getRecordFiles()是一個自定義的方法,後面將會有說明。
1. isSDCardExit = Environment.getExternalStorageState().equals(
2. android.os.Environment.MEDIA_MOUNTED);
3. if (isSDCardExit)
4. iRecAudioDir = Environment.getExternalStorageDirectory();
5. this.getRecordFiles();
6. iAdapter = new ArrayAdapter<String>(this, R.layout.my_simple_list_item,
7. iRecordFiles);
8. /* 將ArrayAdapter添加ListView對象中 */
9. iListView.setAdapter(iAdapter);
對第一個錄音按鈕咱們最須要注意的是在iMediaRecorder.start()以前咱們必須調用iMediaRecorder.prepare()來捕獲和編碼數據,並且prepare()必需要在設置音頻源、編碼器、以及文件格式以後才能調用!
1. iRecordButton.setOnClickListener(new ImageButton.OnClickListener() {
2. @Override
3. public void onClick(View arg0) {
4. try {
5. if (!isSDCardExit) {
6. Toast.makeText(ActivityMain.this, "請插入SD Card",
7. Toast.LENGTH_LONG).show();
8. return;
9. }
10. /* 建立錄音文件 */
11. iRecAudioFile = File.createTempFile(iTempFileNameString,
12. ".amr", iRecAudioDir);
13. iMediaRecorder = new MediaRecorder();
14. /* 設置錄音來源爲MIC */
15. iMediaRecorder
16. .setAudioSource(MediaRecorder.AudioSource.MIC);
17. iMediaRecorder
18. .setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
19. iMediaRecorder
20. .setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
21. iMediaRecorder.setOutputFile(iRecAudioFile
22. .getAbsolutePath());
23. iMediaRecorder.prepare();
24. iMediaRecorder.start();
25. iTextView.setText("正在錄音");
26. iStopButton.setEnabled(true);
27. iPlayButton.setEnabled(false);
28. iDeleteButton.setEnabled(false);
29. isStopRecord = false;
30. } catch (IOException e) {
31. // TODO Auto-generated catch block
32. e.printStackTrace();
33. }
34. }
35. });
在中止錄音的時候須要iMediaRecorder.stop()中止錄音,一旦中止錄音,必須重新配置MediaRecorder才能夠。iMediaRecorder.release()用來釋放和iMediaRecorder對象相關的全部資源。最後把iMediaRecorder賦值爲null。
1. iStopButton.setOnClickListener(new ImageButton.OnClickListener() {
2. @Override
3. public void onClick(View arg0) {
4. // TODO Auto-generated method stub
5. if (iRecAudioFile != null) {
6. /* 中止錄音 */
7. iMediaRecorder.stop();
8. iMediaRecorder.release();
9. iMediaRecorder = null;
10. /* 將錄音頻文件名給Adapter */
11. iAdapter.add(iRecAudioFile.getName());
12. iTextView.setText("中止:" + iRecAudioFile.getName());
13. iStopButton.setEnabled(false);
14. isStopRecord = true;
15. }
16. }
17. });
18. /* 播放 */
19. iPlayButton.setOnClickListener(new ImageButton.OnClickListener() {
20. @Override
21. public void onClick(View arg0) {
22. // TODO Auto-generated method stub
23. if (iPlayFile != null && iPlayFile.exists()) {
24. /* 打開播放程序 */
25. openFile(iPlayFile);
26. }
27. }
28. });
29. /* 刪除 */
30. iDeleteButton.setOnClickListener(new ImageButton.OnClickListener() {
31. @Override
32. public void onClick(View arg0) {
33. // TODO Auto-generated method stub
34. if (iPlayFile != null) {
35. /* 先將Adapter刪除文件名 */
36. iAdapter.remove(iPlayFile.getName());
37. /* 刪除文件 */
38. if (iPlayFile.exists())
39. iPlayFile.delete();
40. iTextView.setText("刪除完成");
41. }
42. }
43. });
44.
45. iListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
46. @Override
47. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
48. long arg3) {
49. /* 當有點擊文件名時將刪除及播放按鈕Enable */
50. iPlayButton.setEnabled(true);
51. iDeleteButton.setEnabled(true);
52. iPlayFile = new File(iRecAudioDir.getAbsolutePath()
53. + File.separator + ((CheckedTextView) arg1).getText());
54. iTextView.setText("您選擇的是:" + ((CheckedTextView) arg1).getText());
55. }
56. });
在Activity的onStop()方法也要加進去釋放iMediaRecorder的語句。
1. @Override
2. protected void onStop() {
3. if (iMediaRecorder != null && !isStopRecord) {
4. /* 中止錄音 */
5. iMediaRecorder.stop();
6. iMediaRecorder.release();
7. iMediaRecorder = null;
8. }
9. super.onStop();
10. }
11.
12. 這是一個自定義方法,目的是從手機存儲卡中取出以.amr結尾的文件。
13. private void getRecordFiles() {
14. iRecordFiles = new ArrayList<String>();
15. if (isSDCardExit) {
16. File files[] = iRecAudioDir.listFiles();
17. if (files != null) {
18. for (int i = ; i < files.length; i++) {
19. if (files[i].getName().indexOf(".") >= ) {
20. String fileS = files[i].getName().substring(
21. files[i].getName().indexOf("."));
22. if (fileS.toLowerCase().equals(".amr"))
23. iRecordFiles.add(files[i].getName());
24. }
25. }
26. }
27. }
28. }
調用系統自帶播放器來播放剛纔錄製好的聲音片斷。OPhone系統會根據文件類型來自動決定使用何種工具來打開對應的文件。固然咱們還能夠用OPhone提供的MediaPlayer類來實現聲音片斷的播放,因爲篇幅有限,這裏再也不介紹。
1. private void openFile(File aFile) {
2. Intent intent = new Intent();
3. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4. intent.setAction(android.content.Intent.ACTION_VIEW);
5. String type = getMIMEType(aFile);
6. intent.setDataAndType(Uri.fromFile(aFile), type);
7. startActivity(intent);
8. }
9.
10. private String getMIMEType(File aFile) {
11. String end = aFile.getName().substring(
12. aFile.getName().lastIndexOf(".") + 1, aFile.getName().length())
13. .toLowerCase();
14. String type = "";
15. if (end.equals("mp3") || end.equals("aac") || end.equals("aac")
16. || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) {
17. type = "audio";
18. } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
19. || end.equals("jpeg")) {
20. type = "image";
21. } else {
22. type = "*";
23. }
24. type += "/*";
25. return type;
26. }
添加權限許可
若是隻是寫好了程序還不算完工,最後咱們須要在AndroidManifest.xml文件中將程序的錄音權限打開!這樣才能成爲一個完整的程序。
1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2. android:versionCode="1"
3. android:versionName="1.0" package="com.ophone.iRecorder">
4. <application
5. android:icon="@drawable/icon"
6. android:label="@string/app_name">
7. <activity android:name=".ActivityMain"
8. android:label="@string/app_name">
9. <intent-filter>
10. <action
11. android:name="android.intent.action.MAIN" />
12. <category
13. android:name="android.intent.category.LAUNCHER" />
14. </intent-filter>
15. </activity>
16. </application>
17. <uses-permission android:name="android.permission.RECORD_AUDIO">
18. </uses-permission>
19. </manifest>