先給大家看一下效果圖吧
這個頻譜是可以根據音樂的起伏變化的,廢話不多說直接上代碼
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監聽中進行調用的,希望可以幫到大家。