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

类似微信说话功能的录音处理代码分享

程序员文章站 2024-02-22 20:02:16
复制代码 代码如下:package com.example.testaudio; import java.io.file; import android.app.act...

复制代码 代码如下:

package com.example.testaudio;

import java.io.file;

import android.app.activity;
import android.media.mediaplayer;
import android.media.mediaplayer.oncompletionlistener;
import android.media.mediarecorder;
import android.os.bundle;
import android.os.environment;
import android.os.handler;
import android.os.message;
import android.util.log;
import android.view.menu;
import android.view.motionevent;
import android.view.view;
import android.view.view.onclicklistener;
import android.view.view.ontouchlistener;
import android.widget.button;
import android.widget.textview;

public class mainactivity extends activity {

 private mediarecorder recoder = null;
 private mediaplayer player = null;
 private string themediapath;

 textview tv = null;
 textview tvrecord = null;
 button testbtn = null;
 button testbtn2 = null;
 button stopbtn = null;
 button playbtn = null;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  tv = (textview)findviewbyid(r.id.textview1);
  tvrecord = (textview)findviewbyid(r.id.tvrecord);
  testbtn = (button)findviewbyid(r.id.button1);
  testbtn2 = (button)findviewbyid(r.id.button2);
  stopbtn = (button)findviewbyid(r.id.buttonstop);
  playbtn = (button)findviewbyid(r.id.buttonplay);

  testbtn2.setontouchlistener(new ontouchlistener() {
   @override
   public boolean ontouch(view v, motionevent event) {
    log.i("testactivity", "setontouchlistener:"+event.getaction());
    switch(event.getaction()) {
     case motionevent.action_up: {
      log.i("testactivity", "停止录音");
      stoprecording();
      break;
     }
     case motionevent.action_down: {
      log.i("testactivity", "开始录音");
      startrecording();
      break;
     }
     default: break;
    }
    return false;
   }
  });

  
  testbtn.setonclicklistener(new onclicklistener() {
   public void onclick(view arg0) {
    startrecording();
    testbtn.setenabled(false);
    stopbtn.setenabled(true);
   }
  });

  stopbtn.setenabled(false);

  stopbtn.setonclicklistener(new onclicklistener() {
   public void onclick(view arg0) {
    stoprecording();
    testbtn.setenabled(true);
    playbtn.setenabled(true);
    stopbtn.setenabled(false);
   }
  });

  
  playbtn.setonclicklistener(new onclicklistener() {
   public void onclick(view arg0) {
    playrecordfile(themediapath);
    stopbtn.setenabled(true);
   }
  });
 }

 protected void playrecordfile(string _file) {
  try {
   file f = new file(_file);
   if(!f.exists()) {
    tv.settext("文件不存在:" + _file);
    return;
   }
  } catch(exception e) {
   log.i("testactivity", e.getmessage());
  }
  try {
   player = new mediaplayer();
   player.setdatasource(_file);
   player.prepare();
   player.setoncompletionlistener(new oncompletionlistener() {
    public void oncompletion(mediaplayer arg0) {
     tv.settext("播放完毕");
     stopbtn.setenabled(false);
    }
   });

   player.start();
  } catch(exception e) {
   log.e("testactivity", "play failed:" + e.getmessage());
  }
 }

 /**
  * 停止录音处理
  */
 protected void stoprecording() {

  if(recoder != null) {
   log.i("testactivity", "停止录音");
   recoder.stop();
   recoder.release();
   recoder = null;
   endtime = system.currenttimemillis();
   _handlerecordcomplete();
  }
  if(player != null) {
   log.i("testactivity", "停止播放");
   player.stop();
   player.release();
   player = null;
  }
 }

 
 /**
  * 开始录音处理
  */
 protected void startrecording() {

  themediapath = environment.getexternalstoragedirectory().getabsolutepath();
  themediapath += "/audiotest.3gp";

  recoder = new mediarecorder();
  recoder.setaudiosource(mediarecorder.audiosource.mic);
  recoder.setoutputformat(mediarecorder.outputformat.three_gpp);
  recoder.setoutputfile(themediapath);
  recoder.setaudioencoder(mediarecorder.audioencoder.amr_nb);

  starttime = system.currenttimemillis();
  updatemicstatus();

  try {
   recoder.prepare();
   recoder.start();
   _handlerecordstart();
  } catch (exception e) {
   log.e("testactivity", "prepared failed:" + e.getmessage());
   _handlerecordstarterror(e);
  }

 }

 //定时器
 private static long maxtime = 30*1000; //30秒
 private long starttime = 0l;
 private long endtime = 0l;
 private final handler mhandler = new handler(); 
    private runnable mupdatemicstatustimer = new runnable() { 
        public void run() { 
         //判断是否超时
         if(starttime > 0 && system.currenttimemillis() - starttime > maxtime) {
          log.e("testactivity", "超时的录音时间,直接停止");
          stoprecording();
          return;
         }

         //更新分贝状态
            updatemicstatus(); 
        } 
    }; 

    /**
     * 更新话筒状态 分贝是也就是相对响度 分贝的计算公式k=20lg(vo/vi) vo当前振幅值 vi基准值为600:我是怎么制定基准值的呢? 当20
     * * math.log10(mmediarecorder.getmaxamplitude() / vi)==0的时候vi就是我所需要的基准值
     * 当我不对着麦克风说任何话的时候,测试获得的mmediarecorder.getmaxamplitude()值即为基准值。
     * log.i("mic_", "麦克风的基准值:" + mmediarecorder.getmaxamplitude());前提时不对麦克风说任何话
     */ 
    private int base = 600; 
    private int space = 300;// 间隔取样时间

    private void updatemicstatus() { 
        if (recoder != null) { 
            // int vusize = 10 * mmediarecorder.getmaxamplitude() / 32768; 
            int ratio = recoder.getmaxamplitude() / base; 
            int db = 0;// 分贝 
            if (ratio > 1) 
                db = (int) (20 * math.log10(ratio)); 

           
            _handlerecordvoice(db);

            mhandler.postdelayed(mupdatemicstatustimer, space); 
            /*
             * if (db > 1) { vusize = (int) (20 * math.log10(db)); log.i("mic_",
             * "麦克风的音量的大小:" + vusize); } else log.i("mic_", "麦克风的音量的大小:" + 0);
             */ 
        } 
    }
 

 private void _handlerecordstart() {
  //开始录音的接收函数
  tv.settext("开始录音...");
  //starttime 开始时间
 }

 private void _handlerecordstarterror(exception e) {
  //开始录音的接收函数失败
  tv.settext("开始录音失败:" + e.getmessage());
 }

 private void _handlerecordcomplete() {
  //结束录音
  tv.settext("停止录音:" + themediapath);
 }

 private void _handlerecordvoice(int _db) {
  //声音事件侦听,转换成分贝
  tvrecord.settext(""+_db);
 }

 @override
 public boolean oncreateoptionsmenu(menu menu) {
  // inflate the menu; this adds items to the action bar if it is present.
  getmenuinflater().inflate(r.menu.main, menu);
  return true;
 }

}