jul
jul

Reputation: 37484

Real time data visualization in Android

I'm working on an audio vu meter and I'd like to get something like the image shown below, with audio amplitude shown in real-time.

I know how to get the audio amplitude for each channel, but I'm not sure how to do a fast enough display of the colored rectangles.

My first idea is to of have a View with a background color for each rectangle and showing/hiding it according to the amplitude.

Has anybody already tried that? Would it be fast enough for displaying the amplitude every 50 or 100ms?

What's the fastest way of achieving that?

Thanks you

enter image description here

Upvotes: 3

Views: 1137

Answers (1)

Renard
Renard

Reputation: 6929

So you want to make as many views as you have rectangle and change their visibility? Don't do that. It will be a mess inside your layout. Instead make a custom view and override onDraw(). Inside onDraw you use canvas.drawRect() to draw the rectangles. You will get easily 30-60 frames per second this way. This is a simple and uncomplete example but should get you on the right track.

private class AmplitudeView extends View {

    private int mWidth;
    private int mHeight;
    private Paint mRectPaint;

    public AmplitudeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRectPaint = new Paint() {
            {
                setStyle(Style.FILL);
            }
        };
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int numRects = 10;
        int red = 255;
        int green = 0;
        int incr = 255/numRects;
        for (int i = 0; i< numRects;i++){
            //TODO calculate color based on amplitude
            mRectPaint.setColor(Color.argb(0xff, red, green, 0));
            //TODO calculate rectangle
            canvas.drawRect(r, mRectPaint);
            red-=incr;
            green+=incr;
        }
    }
}

Upvotes: 2

Related Questions