在 Android 中,可以使用 AudioTrack 类以平滑的方式显示音频波形。
以下是一个简单的示例代码:
private void renderWaveform(AudioTrack audioTrack, short[] waveform) {
final int sampleRate = audioTrack.getSampleRate();
final int channelCount = audioTrack.getChannelCount();
final int waveformSize = waveform.length;
final float[] waveformPoints = new float[waveformSize * 4];
for (int i = 0; i < waveformSize; i++) {
final float level = waveform[i] / 32767.0f;
final int x = (int) (((float) i / (float) waveformSize) * (float) getWidth());
final int y = (int) ((0.5f + (level * 0.5f)) * (float) getHeight());
waveformPoints[(i * 4)] = x;
waveformPoints[(i * 4) + 1] = (y * channelCount) - 1;
waveformPoints[(i * 4) + 2] = x;
waveformPoints[(i * 4) + 3] = (y * channelCount) + 1;
}
final Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(2.0f);
final Canvas canvas = new Canvas();
final Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
canvas.drawLines(waveformPoints, paint);
audioTrack.write(bitmapToByteArray(bitmap), 0, bitmap.getByteCount());
}
private byte[] bitmapToByteArray(Bitmap bitmap) {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.ARGB_8888, 100, outputStream);
return outputStream.toByteArray();
}