android自定义View之音乐播放器的频谱

先给大家看一下效果图吧


这个频谱是可以根据音乐的起伏变化的,废话不多说直接上代码

public class BarGraphViewextends View {

byte[]y =new byte[1024];

Rect[]rects =new Rect[1024];

Paintpaint =new Paint();

Randomrandom =new Random();

private Numbernumber;

public class Number {

public int num =y.length;

}

public void setY(byte[] y) {

this.y = y;

}

public BarGraphView(Context context,@Nullable AttributeSet attrs) {

this(context, attrs,0);

}

public BarGraphView(Context context,@Nullable AttributeSet attrs,int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

private void init() {

number =new Number();

int width = DensityUtil.dip2px(getContext(),1080);

int height = getHeight();

int i1 = width /number.num;

for (int i =0; i

rects[i] =new Rect(i * i1, (int) (height - Math.abs(y[i]) *1.5), i * i1 +10, height);

}

paint.setColor(getResources().getColor(R.color.white));

paint.setStyle(Paint.Style.STROKE);

paint.setStrokeWidth(1);

}

@Override

    protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

int heightSize = MeasureSpec.getSize(heightMeasureSpec);

int widthMode = MeasureSpec.getMode(widthMeasureSpec);

int heightMode = MeasureSpec.getMode(heightMeasureSpec);

init();

}

@Override

    public void invalidate() {

init();

super.invalidate();

}

@Override

    protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

// 随机颜色

        int[] ranColor = {0xffff00ff,0xffffffff,0xff00ffff,0x00ffffff,0x00eeffff,0x00ffeeff};

for (int i =0; i

paint.setColor(ranColor[random.nextInt(6)]);

canvas.drawRect(rects[i],paint);

}

}

int y1;

public void setY1(int y1) {

this.y1 = y1;

}

public void start() {

for (int i =0; i

ObjectAnimator objectAnimator = ObjectAnimator.ofInt(this,"y1",0,y[i]);

objectAnimator.start();

objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());

objectAnimator.setDuration(300);

int finalI = i;

objectAnimator.addUpdateListener(animation -> {

y[finalI] = (byte)y1;

invalidate();

});

objectAnimator.start();

}

}

}

这个是用来做一些炫酷的音乐播放效果的,不过暂时还是一个未成品,没有一些自定义属性进行控制,大家使用的时候可以对它进行优化一下,内容比较简单,主要是想跟大家分享一下。

调用起来也是很简单的,要配合mediaplayer中的visualizer来使用,visualizer是用来获取音乐频谱的,如果不知道怎么用可以去百度搜索一下,下面是调用这个VIew的方法:

barGraphView.setY(waveform);

barGraphView.invalidate();

barGraphView.start();

这是在visualizer监听中进行调用的,希望可以帮到大家。

你可能感兴趣的:(android自定义View之音乐播放器的频谱)