Android话筒音频采样和使用

Android手机话筒采样有部分代码是在网上找的,具体不记得了。

使用采样结果以及是自己的app的功能代码:

1. 在一部分app中会需要对话筒的音频输入获取使用,比如之前很火的吹裙子;

2. 采样线程:

public class MicroLevelRunnable implements Runnable {
 private static final String tag = "MicroLevelThread";
 private AudioRecord ar;
 private short bs;
 // 11 025 Hz、8 bit的声音称为电话音质;
 // 22 050 Hz、16 bit的声音称为广播音质;
 // 44 100 Hz、16 bit已达到CD的音质了[4]。
 private final int SAMPLE_RATE_IN_HZ = 22050;
 private boolean isRun = false;

 public static final int msg_v = 0;
 public static final int msg_vv = 1;
 public static final int msg_vf = 2;
 public static final int msg_vo = 3;

 public static final int page_need_water = 10;

 public static int bubble_speed = 2;// 每N次调用,出一个bubble

 public MicroLevelRunnable() {
  super();
 }
 
 public void stop(){
  isRun = false;
  ar.stop();
  ar.release();
  ar = null;
 }

 public void run() {
  bs = (short)AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ,
    AudioFormat.CHANNEL_CONFIGURATION_MONO,
    AudioFormat.ENCODING_PCM_16BIT);
  ar = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ,
    AudioFormat.CHANNEL_CONFIGURATION_MONO,
    AudioFormat.ENCODING_PCM_16BIT, bs);
  // 用于读取的
  ar.startRecording();
  short[] buffer = new short[bs];
  isRun = true;
  int speed = 1;
  while (true) {
   if (!isRun) {
    try {
     synchronized (this) {
      Log.v(tag, "wait..");
      this.wait();
     }
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
   speed++;
   int r = ar.read(buffer, 0, bs);
   int v = 0;
   for (int i = 0; i < buffer.length; i++) {
    v += buffer[i] * buffer[i];
   }
   int value = (int) (Math.abs((int) (v / (float) r) / 10000) >> 1);

   double dB = 10 * Math.log10(Math.abs(v) / (double) r);

   Message msg = new Message();
   msg.what = msg_v;
   msg.arg1 = value;
   msg.arg2 = (int) dB;
   // -------------------------------------------
   // 用以下方法区分是否是吹气,缺点是可以模拟
   // DB白噪低于50为噪音,大于60为无效
   // value值低于38为无声,大于60无无效

   if (speed > bubble_speed) {
    BubbleMain.MainHandle.sendMessage(msg);
    speed = 1;
   }
  }
 }

}

3. 启动采样线程:

  mRunnable = new MicroLevelRunnable();
  mThread = new Thread(mRunnable);
  mThread.start();

4. 本人的android应用【http://openbox.mobilem.360.cn/index/d/sid/341284 http://zhushou.360.cn/detail/index/soft_id/341284】 吹泡泡中就使用了如上功能模块

该应用是web+android组件的典型应用,吹泡泡的展现是优化修改过的web程序,通过webview接口以及话筒采样线程的结合,实现在手机上吹出泡泡的效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值