Android音頻錄製MediaRecorder之簡易的錄音軟體實現代碼_Android

來源:互聯網
上載者:User

使用MediaRecorder的步驟:
1、建立MediaRecorder對象
2、調用MediRecorder對象的setAudioSource()方法設定聲音的來源,一般傳入MediaRecorder.MIC
3、調用MediaRecorder對象的setOutputFormat()設定所錄製的音頻檔案的格式
4、調用MediaRecorder對象的setAudioRncoder()、setAudioEncodingBitRate(int bitRate)、setAudioSamlingRate(int SamplingRate)設定所錄音的編碼格式、編碼位率、採樣率等,
5、調用MediaRecorder對象的setOutputFile(String path)方法設定錄製的音頻檔案的儲存位置
6、調用MediaRecoder對象的Prepare()方法準備錄製
7、調用MediaRecoder對象的start()方法開始錄製
8、調用MediaRecoder對象的stop()方法停止錄製,並調用release()方法釋放資源

執行個體:

複製代碼 代碼如下:

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

複製代碼 代碼如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   
    <LinearLayout
        android:id="@+id/li1"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button android:id="@+id/start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/start"/>
         <Button android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/stop"/>
    </LinearLayout>
    <ListView
        android:id="@+id/list"
        android:layout_below="@id/li1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></ListView>

</RelativeLayout>

複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/show_file_name" />

    <Button
        android:id="@+id/bt_list_play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play"/>
    <Button  android:id="@+id/bt_list_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/list_stop"/>

</LinearLayout>

複製代碼 代碼如下:

package com.android.xiong.mediarecordertest;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

 private Button start;
 private Button stop;
 private ListView listView;
 // 錄音檔案播放
 private MediaPlayer myPlayer;
 // 錄音
 private MediaRecorder myRecorder;
 // 音頻檔案儲存地址
 private String path;
 private String paths = path;
 private File saveFilePath;
 // 所錄音的檔案
 String[] listFile = null;

 ShowRecorderAdpter showRecord;
 AlertDialog aler = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  start = (Button) findViewById(R.id.start);
  stop = (Button) findViewById(R.id.stop);
  listView = (ListView) findViewById(R.id.list);
  myPlayer = new MediaPlayer();
  myRecorder = new MediaRecorder();
  // 從麥克風源進行錄音
  myRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
  // 設定輸出格式
  myRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
  // 設定編碼格式
  myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
  showRecord = new ShowRecorderAdpter();
  if (Environment.getExternalStorageState().equals(
    Environment.MEDIA_MOUNTED)) {
   try {
    path = Environment.getExternalStorageDirectory()
      .getCanonicalPath().toString()
      + "/XIONGRECORDERS";
    File files = new File(path);
    if (!files.exists()) {
     files.mkdir();
    }
    listFile = files.list();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  start.setOnClickListener(this);
  stop.setOnClickListener(this);
  if (listFile != null) {
   listView.setAdapter(showRecord);
  }

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 class ShowRecorderAdpter extends BaseAdapter {

  @Override
  public int getCount() {
   return listFile.length;
  }

  @Override
  public Object getItem(int arg0) {
   return arg0;
  }

  @Override
  public long getItemId(int arg0) {
   return arg0;

  }

  @Override
  public View getView(final int postion, View arg1, ViewGroup arg2) {
   View views = LayoutInflater.from(MainActivity.this).inflate(
     R.layout.list_show_filerecorder, null);
   TextView filename = (TextView) views
     .findViewById(R.id.show_file_name);
   Button plays = (Button) views.findViewById(R.id.bt_list_play);
   Button stop = (Button) views.findViewById(R.id.bt_list_stop);

   filename.setText(listFile[postion]);
   // 播放錄音
   plays.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
     try {
      myPlayer.reset();
      myPlayer.setDataSource(path + "/" + listFile[postion]);
      if (!myPlayer.isPlaying()) {

       myPlayer.prepare();
       myPlayer.start();
      } else {
       myPlayer.pause();
      }

     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   });
   // 停止播放
   stop.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
     if (myPlayer.isPlaying()) {
      myPlayer.stop();
     }
    }
   });
   return views;
  }

 }

 @Override
 public void onClick(View v) {
  switch (v.getId()) {
  case R.id.start:
   final EditText filename = new EditText(this);
   Builder alerBuidler = new Builder(this);
   alerBuidler
     .setTitle("請輸入要儲存的檔案名稱")
     .setView(filename)
     .setPositiveButton("確定",
       new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog,
          int which) {
         String text = filename.getText().toString();
         try {
          paths = path
            + "/"
            + text
            + new SimpleDateFormat(
              "yyyyMMddHHmmss").format(System
              .currentTimeMillis())
            + ".amr";
          saveFilePath = new File(paths);
          myRecorder.setOutputFile(saveFilePath
            .getAbsolutePath());
          saveFilePath.createNewFile();
          myRecorder.prepare();
          // 開始錄音
          myRecorder.start();
          start.setText("正在錄音中。。");
          start.setEnabled(false);
          aler.dismiss();
          // 重新讀取 檔案
          File files = new File(path);
          listFile = files.list();
          // 重新整理ListView
          showRecord.notifyDataSetChanged();
         } catch (Exception e) {
          e.printStackTrace();
         }

        }
       });
   aler = alerBuidler.create();
   aler.setCanceledOnTouchOutside(false);
   aler.show();
   break;
  case R.id.stop:
   if (saveFilePath.exists() && saveFilePath != null) {
    myRecorder.stop();
    myRecorder.release();
    // 判斷是否儲存 如果不儲存則刪除
    new AlertDialog.Builder(this)
      .setTitle("是否儲存該錄音")
      .setPositiveButton("確定", null)
      .setNegativeButton("取消",
        new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog,
           int which) {
          saveFilePath.delete();
          // 重新讀取 檔案
          File files = new File(path);
          listFile = files.list();
          // 重新整理ListView
          showRecord.notifyDataSetChanged();
         }
        }).show();

   }
   start.setText("錄音");
   start.setEnabled(true);
  default:
   break;
  }

 }

 @Override
 protected void onDestroy() {
  // 釋放資源
  if (myPlayer.isPlaying()) {
   myPlayer.stop();
   myPlayer.release();
  }
  myPlayer.release();
  myRecorder.release();
  super.onDestroy();
 }

}

源碼下載:http://xiazai.jb51.net/201401/yuanma/MediaRecorderTest(jb51.net).rar

聯繫我們

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