最近在仿微信开发聊天界面:开发到一个有意思的小东西,简单写一写。就是录音声波这块。
首先先添加几个图片Android开发:仿微信 录音声波_android

Android开发:仿微信 录音声波_android_02

Android开发:仿微信 录音声波_Android_03

添加如上三个声波图表
之后建立一个数组

private int[] images = {R.mipmap.ico_yuyinhui_1,R.mipmap.ico_yuyinhui_2,R.mipmap.ico_yuyinhui_3};

有了数组后就可以建立一个handler来刷新界面了

private final Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case 0:
                case 1:
                case 2:micImage.setBackground(getResources().getDrawable(micImages[what],getResources().newTheme()));
                    break;
            }

        };
    };

之后建立主要代码区

private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };
 private int BASE = 1;  
    private int SPACE = 100;// 间隔取样时间  
    private void updateMicStatus() {  
        if (mMediaRecorder != null) {  
            double ratio = (double)mMediaRecorder.getMaxAmplitude() /BASE;  
            double db = 0;// 分贝  
            if (ratio > 1)  
                db = 20 * Math.log10(ratio);  
uiHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
            //分贝在50 - 90 之间
            int min = db - 50;
            if(min<0){
                min = 0;
            }
            int step = (min)/((90-50)/3);
            if(step>2){
                step = 2;
            }
            Logger.d(step+"step updateMicStatus");
            uiHandler.sendEmptyMessage(step);
        }  
    }  

特别要注意的是要在测试完后移除线程

        uiHandler.removeCallbacks(mUpdateMicStatusTimer);

具体layout代码我就不写了,非常简单。
如果有什么问题在下面提就好了。
效果图如下
Android开发:仿微信 录音声波_android开发_04Android开发:仿微信 录音声波_android_05