zoukankan      html  css  js  c++  java
  • Android音频录制MediaRecorder之简易的录音软件实现代码(转)

    原文:http://www.jb51.net/article/46182.htm

    Android音频录制MediaRecorder之简易的录音软件实现代码

    这篇文章主要介绍了Android音频录制MediaRecorder之简易的录音软件实现代码,有需要的朋友可以参考一下

    使用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

  • 相关阅读:
    WCF 限流 Throttling
    VS2010安装了Hide Main Menu 插件
    ASP.NET MVC基于标注特性的Model验证:将ValidationAttribute应用到参数上
    UML面向对象分析设计
    我的WCF开发框架简化版及基于NET.TCP传输方式的实现
    一周最新示例代码回顾 (6/4–6/10)
    Windows Azure 上的托管服务CDN (下) Hosted Service
    计算机考研的调查和改进建议
    并发编程中的重重量级模型和轻量级模型
    JIRA_5_和GreenHopper5.9破解及汉化
  • 原文地址:https://www.cnblogs.com/mochaMM/p/5073848.html
Copyright © 2011-2022 走看看