Search code examples
javaandroidmicrophone

Android Mic Volume Meter


I'm writing an app that requires getting the mic level to create a sound meter. I have found this: Android Media Player Decibel Reading. I still need to create a meter to display the current level, out of 100% kind of deal. So a bar that the higher it gets it gets redder for example. Just getting the code to display the level is great.

In the link above there is a method for getting the current decibel reading, however it appears to be something that I would need to possibly run in a separate thread and update it constantly. I was reading into a VU meter but have no clue where to start.

Thanks in advance!


Solution

  • Okay I'm assuming your working with the code you linked to in your question.

    So this meter will have to change its size and colour on the fly depending on the value of amplitude.

    To draw the shape extend the View class and override the onDraw method as shown below

    float x,y; //CONSTANTS FOR WHERE YOU WANT YOUR BAR TO BE
    float baseWidth; // This is the width of one block. 
                     //Number of blocks together will be your rectangle
    float nwidth;     //This is the number of blocks varying according to amplitude
    float height;    //CONSTANT HEIGHT
    Paint color=new Paint();     
    
    //For drawing meter
    public void onDraw(Canvas c){
      changeColorAndSize();
      Rect rect = new Rect(x, y, x + (baseWidth*nwidth), y + height);
      shapeDrawable.setBounds(rect);
      shapeDrawable.getPaint().set(paint);
      shapeDrawable.draw(canvas);
    
    }
    
    public void changeColorAndSize(){
           double amp=getAmplitude();
           nWidth=amp;
           paint.setARGB (a, r*(Integer.parseInt(amp)), g, b);
          //This will change the redness of the bar. a,g and b will have to be set by you
    
    }
    
    public double getAmplitude() {
            if (mRecorder != null)
                    return  (mRecorder.getMaxAmplitude());
            else
                    return 0;
    }
    

    To make the meter change every 'x' seconds you will have to call postInvalidate() repeatedly

    OR

    Use an Animation, and call startAnimation() on it from your View.