欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-06-29 09:26:33
使用mediarecorder的步骤:1、创建mediarecorder对象2、调用medirecorder对象的setaudiosource()方法设置声音的来源,一般传...

使用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()方法释放资源

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

实例:

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

复制代码 代码如下:

    <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