Search code examples
androidaudiocanvaswaveform

Which is the best approach for dynamic drawing in Android?


I want to make a waveform drawing for an audio recorder in Android. The usual one with lines/bars, like this one:

enter image description here

More importantly, I want it live, while the song is being recorded. My app already computes the RMS through AudioRecord. But I am not sure which is the best approach for the actual drawing in terms of processing, resources, battery, etc.

The Visualizer does not show anything meaningful, IMO (are those graphs more or less random stuff??).

I've seen the canvas approach and the layout approach (there are probably more?). In the layout approach you add thin vertical layouts in a horizontal layout. The advantage is that you don't need to redraw the whole thing each 1/n secs, you just add one layout each 1/n secs... but you need hundreds of layouts (depending on n). In the canvas layout, you need to redraw the whole thing (right??) n times per second. Some even create bitmaps for each drawing...

So, which is cheaper, and why? Is there anything better nowadays? How much frequency update (i.e., n) is too much for generic low end devices?

EDIT1

Thanks to the beautiful trick @cactustictacs taught me in his answer, I was able to implement this with ease. Yet, the image is strangely rendered kind of "blurry by movement":

enter image description here

The waveform runs from right to left. You can easily see the blur movement, and the left-most and right-most pixels get "contaminated" by the other end. I guess I can just cut both extremes...

This renders better if I make my Bitmap bigger (i.e., making widthBitmap bigger), but then the onDraw will be heavier...

This is my full code:

package com.floritfoto.apps.ave;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;

import java.util.Arrays;

public class Waveform extends androidx.appcompat.widget.AppCompatImageView {
    //private float lastPosition = 0.5f; // 0.5 for drawLine method, 0 for the others
    private int lastPosition = 0;
    private final int widthBitmap = 50;
    private final int heightBitmap = 80;
    private final int[] transpixels = new int[heightBitmap];
    private final int[] whitepixels = new int[heightBitmap];
    //private float top, bot;            // float for drawLine method, int for the others
    private int aux, top;
    //private float lpf;
    private int width = widthBitmap;
    private float proportionW = (float) (width/widthBitmap);
    Boolean firstLoopIsFinished = false;
    Bitmap MyBitmap = Bitmap.createBitmap(widthBitmap, heightBitmap, Bitmap.Config.ARGB_8888);
    //Canvas canvasB = new Canvas(MyBitmap);
    Paint MyPaint = new Paint();
    Paint MyPaintTrans = new Paint();
    Rect rectLbit, rectRbit, rectLdest, rectRdest;

    public Waveform(Context context, AttributeSet attrs) {
        super(context, attrs);
        MyPaint.setColor(0xffFFFFFF);
        MyPaint.setStrokeWidth(1);
        MyPaintTrans.setColor(0xFF202020);
        MyPaintTrans.setStrokeWidth(1);
        Arrays.fill(transpixels, 0xFF202020);
        Arrays.fill(whitepixels, 0xFFFFFFFF);
    }

    public void drawNewBar() {
        // For drawRect or drawLine
        /*
        top = ((1.0f - Register.tone) * heightBitmap / 2.0f);
        bot = ((1.0f + Register.tone) * heightBitmap / 2.0f);

        // Using drawRect
        //if (firstLoopIsFinished) canvasB.drawRect(lastPosition, 0, lastPosition+1, heightBitmap, MyPaintTrans);  // Delete last stuff
        //canvasB.drawRect(lastPosition, top, lastPosition+1, bot, MyPaint);

        // Using drawLine
        if (firstLoopIsFinished) canvasB.drawLine(lastPosition, 0, lastPosition, heightBitmap, MyPaintTrans);  // Delete previous stuff
        canvasB.drawLine(lastPosition ,top, lastPosition, bot, MyPaint);
        */
        // Using setPixel (no tiene sentido, mucho mejor setPixels.
        /*
        int top = (int) ((1.0f - Register.tone) * heightBitmap / 2.0f);
        int bot = (int) ((1.0f + Register.tone) * heightBitmap / 2.0f);
        if (firstLoopIsFinished) {
            for (int i = 0; i < top; ++i) {
                MyBitmap.setPixel(lastPosition, i, 0xFF202020);
                MyBitmap.setPixel(lastPosition, heightBitmap - i-1, 0xFF202020);
            }
        }
        for (int i = top ; i < bot ; ++i) {
            MyBitmap.setPixel(lastPosition,i,0xffFFFFFF);
        }
        //System.out.println("############## "+top+" "+bot);
        */
        // Using setPixels. Works!!
        top = (int) ((1.0f - Register.tone) * heightBitmap / 2.0f);
        if (firstLoopIsFinished)
            MyBitmap.setPixels(transpixels,0,1,lastPosition,0,1,heightBitmap);
        MyBitmap.setPixels(whitepixels, top,1, lastPosition, top,1,heightBitmap-2*top);

        lastPosition++;

        aux = (int) (width - proportionW * (lastPosition));
        rectLbit.right = lastPosition;
        rectRbit.left = lastPosition;
        rectLdest.right = aux;
        rectRdest.left = aux;

        if (lastPosition >= widthBitmap) { firstLoopIsFinished = true; lastPosition = 0; }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        proportionW = (float) width/widthBitmap;
        rectLbit = new Rect(0, 0, widthBitmap, heightBitmap);
        rectRbit = new Rect(0, 0, widthBitmap, heightBitmap);
        rectLdest = new Rect(0, 0, width, h);
        rectRdest = new Rect(0, 0, width, h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawNewBar();
        canvas.drawBitmap(MyBitmap, rectLbit, rectRdest, MyPaint);
        canvas.drawBitmap(MyBitmap, rectRbit, rectLdest, MyPaint);
    }
}

EDIT2 I was able to prevent the blurring just using null as Paint in the canvas.drawBitmap:

        canvas.drawBitmap(MyBitmap, rectLbit, rectRdest, null);
        canvas.drawBitmap(MyBitmap, rectRbit, rectLdest, null);

No Paints needed.


Solution

  • Your basic custom view approach would be to implement onDraw and redraw your current data each frame. You'd probably keep some kind of circular Buffer holding your most recent n amplitude values, so each frame you'd iterate over those, and use drawRect to draw the bars (you'd calculate things like width, height scaling, start and end positions etc in onSizeChanged, and use those values when defining the coordinates for the Rects).

    That in itself might be fine! The only way you can really tell how expensive draw calls are is to benchmark them, so you could try this approach out and see how it goes. Profile it to see how much time it takes, how much the CPU spikes etc.

    There are a few things you can do to make onDraw as efficient as possible, mostly things like avoiding object allocations - so watch out for loop functions that create Iterators, and in the same way you're supposed to create a Paint once instead of creating them over and over in onDraw, you could reuse a single Rect object by setting its coordinates for each bar you need to draw.


    Another approach you could try is creating a working Bitmap in your custom view, which you control, and calling drawBitmap inside onDraw to paint it onto the Canvas. That should be a pretty inexpensive call, and it can easily be stretched as required to fit the view.

    The idea there, is that very time you get new data, you paint it onto the bitmap. Because of how your waveform looks (like blocks), and the fact you can scale it up, really all you need is a single vertical line of pixels for each value, right? So as the data comes in, you paint an extra line onto your already-existing bitmap, adding to the image. Instead of painting the entire waveform block by block every frame, you're just adding the new blocks.


    The complication there is when you "fill" the bitmap - now you have to "shift" all the pixels to the left, dropping the oldest ones on the left side, so you can draw the new ones on the right. So you'll need a way to do that!

    Another approach would be something similar to the circular buffer idea. If you don't know what that is, the idea is you take a normal buffer with a start and an end, but you treat one of the indices as your data's start point, wrap around to 0 when you hit the last index of the buffer, and stop when you hit the index you're calling your end point:

    Partially filled buffer:
    
    |start
    123400
       |end
    Data: 1234
    
    Full buffer:
    
    |start
    123456
         |end
    Data: 123456
    
    After adding one more item:
    
     |start
    723456
    |end
    Data: 234567
    

    See how once it's full, you shift the start and end one step "right", wrapping around if necessary? So you always have the most recent 6 values added. You just have to handle reading from the correct index ranges, from start -> lastIndex and then firstIndex -> end

    You could do the same thing with a bitmap - start "filling" it from the left, increasing end so you can draw the next vertical line. Once it's full, start filling from the left by moving end there. When you actually draw the bitmap, instead of drawing the whole thing as-is (723456) you draw it in two parts (23456 then 7). Make sense? When you draw a bitmap to the canvas, there's a call that takes a source Rect and a destination one, so you can draw it in two chunks.


    You could always redraw the bitmap from scratch each frame (clear it and draw the vertical lines), so you're basically redrawing your whole data buffer each time. Probably still faster than the drawRect approach for each value, but honestly not much easier than the "treat the bitmap as another circular buffer" method. If you're already managing one circular buffer, it's not much more work - since the buffer and the bitmap will have the same number of values (horizontal pixels in the bitmap's case) you can use the same start and end values for both