要實現音頻波形的動畫效果,可以通過Android的AudioTrack類來實現。以下是一個簡單的示例代碼:
public class WaveformView extends View {
private byte[] mWaveform;
private Paint mPaint;
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(2);
}
public void setWaveform(byte[] waveform) {
mWaveform = waveform;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mWaveform == null) {
return;
}
int width = getWidth();
int height = getHeight();
Path path = new Path();
path.moveTo(0, height / 2);
for (int i = 0; i < mWaveform.length; i++) {
float x = i * width / mWaveform.length;
float y = height / 2 + mWaveform[i] * height / 2 / 128;
path.lineTo(x, y);
}
canvas.drawPath(path, mPaint);
}
}
在Activity中使用WaveformView并傳入音頻數據即可看到波形動畫效果:
public class MainActivity extends AppCompatActivity {
private WaveformView mWaveformView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWaveformView = findViewById(R.id.waveformView);
// 傳入音頻數據
byte[] waveform = generateWaveform();
mWaveformView.setWaveform(waveform);
}
private byte[] generateWaveform() {
// 生成音頻數據的邏輯,例如解碼音頻文件、錄制音頻等
return new byte[1024];
}
}
在generateWaveform方法中,需要生成音頻數據的邏輯,例如解碼音頻文件、錄制音頻等。然后將生成的音頻數據傳入WaveformView中即可看到音頻波形的動畫效果。