android 录音波纹
时间: 2023-07-22 19:25:15 浏览: 88
android录音绘制波形
要在 Android 应用中实现录音波纹,可以使用 Android 的 AudioRecord 类来获取录音数据,然后将其传递给一个自定义视图来绘制波形。以下是一个简单的实现步骤:
1.创建一个自定义视图,继承自 View 类。
2.在自定义视图中实现一个方法来绘制波形。
3.在 Activity 中创建一个线程,用于从 AudioRecord 中读取录音数据,并将其传递给自定义视图。
4.在 Activity 的 onStart() 方法中启动线程,在 onStop() 方法中停止线程。
以下是一个简单的实现代码:
```
public class WaveformView extends View {
private Paint paint;
private float[] amplitudes;
public WaveformView(Context context) {
super(context);
init();
}
public WaveformView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(3);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (amplitudes == null) {
return;
}
int width = getWidth();
int height = getHeight();
int centerY = height / 2;
for (int i = 0; i < amplitudes.length; i++) {
float x = width * i / (float) amplitudes.length;
float y = centerY + amplitudes[i] * height / 2;
canvas.drawLine(x, centerY, x, y, paint);
}
}
public void setAmplitudes(float[] amplitudes) {
this.amplitudes = amplitudes;
invalidate();
}
}
public class MainActivity extends Activity {
private WaveformView waveformView;
private AudioRecord audioRecord;
private boolean isRecording;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
waveformView = (WaveformView) findViewById(R.id.waveform_view);
int bufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
}
@Override
protected void onStart() {
super.onStart();
isRecording = true;
final int bufferSize = audioRecord.getBufferSizeInFrames();
final float[] amplitudes = new float[bufferSize];
new Thread(new Runnable() {
@Override
public void run() {
audioRecord.startRecording();
while (isRecording) {
int num = audioRecord.read(amplitudes, 0, bufferSize,
AudioRecord.READ_BLOCKING);
waveformView.setAmplitudes(Arrays.copyOf(amplitudes, num));
}
audioRecord.stop();
audioRecord.release();
}
}).start();
}
@Override
protected void onStop() {
isRecording = false;
super.onStop();
}
}
```
在这个例子中,WaveformView 类是自定义视图,它负责绘制波形。MainActivity 类是 Activity,它创建了一个 AudioRecord 对象并启动了一个线程来获取录音数据,并将其传递给 WaveformView 类来显示波形。注意,线程必须在 onStart() 方法中启动,在 onStop() 方法中停止。
阅读全文