需要配置权限话筒权限
public class MicroLevelRunnable implements Runnable{ @SuppressLint("HandlerLeak") Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what==msg_v){ int db = msg.arg2; int value = msg.arg1; if (db<50){ mtag=true; } if (60>db&&db>50&&value<100){ if (mtag){ setToast(value); } mtag=false; } } } }; public boolean mtag=true; 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 = 11025; private boolean isRun = false; public static final int msg_v = 0; 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) { handler.sendMessage(msg); speed = 1; } } } public void setToast(int mag){ Toast toast = Toast.makeText(MyAppliction.Acontext,"",Toast.LENGTH_SHORT); toast.setText(mag+"--"); toast.show(); } }