draw Audio onto Canvas - Android android.graphics

Android examples for android.graphics:Canvas

Description

draw Audio onto Canvas

Demo Code

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.widget.ImageView;

public class Main {

  public static void drawAudio(short[] track, Canvas canvas, Paint paint) {
    drawAudio(track, canvas, paint, audioRange(track));
  }//from   www  .j  av  a  2s.c  om

  public static void drawAudio(short[] track, Canvas canvas, Paint paint, short range) {
    // range is needed to choose an appropriate vertical scale for the drawing
    if (range == 0)
      return;
    Path mPath = new Path();
    int height = canvas.getHeight();
    int width = canvas.getWidth();
    mPath.moveTo(0, canvas.getHeight() / 2);
    for (int i = 0; i < track.length; i++) {
      mPath.lineTo(width * i / track.length, track[i] * height / range / 2 + height / 2);
    }
    mPath.moveTo(0, height / 2);
    canvas.drawPath(mPath, paint);
  }

  public static void drawAudio(short[] track, ImageView v, Paint paint) {
    Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmp);
    drawAudio(track, canvas, paint);
    v.setImageBitmap(bmp);
  }

  public static short audioRange(short[] track) { // Returns largest amplitude ("volume") of an audio track
    short range = 0;
    for (int i = 0; i < track.length; i++) {
      if (Math.abs(track[i]) > range)
        range = (short) Math.abs(track[i]);
    }
    return range;
  }

}

Related Tutorials