android 录音功能实现
时间: 2023-07-28 10:07:37 浏览: 98
在 Android 中实现录音功能,可以使用 `MediaRecorder` 类或 `AudioRecord` 类。这里给出 `AudioRecord` 的实现示例。
首先,在 AndroidManifest.xml 文件中添加录音权限:
```xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
```
然后,创建一个 `AudioRecord` 对象并开始录音:
```java
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
public class AudioRecorder {
private static final String TAG = AudioRecorder.class.getSimpleName();
private static final int SAMPLE_RATE = 16000;
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
private AudioRecord audioRecord;
private byte[] buffer;
private boolean isRecording;
private Handler handler;
private Callback callback;
public AudioRecorder() {
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, BUFFER_SIZE);
buffer = new byte[BUFFER_SIZE];
handler = new Handler(Looper.getMainLooper());
}
public void setCallback(Callback callback) {
this.callback = callback;
}
public void start() {
if (isRecording) {
return;
}
audioRecord.startRecording();
isRecording = true;
new Thread(() -> {
while (isRecording) {
int bytes = audioRecord.read(buffer, 0, buffer.length);
if (bytes > 0 && callback != null) {
handler.post(() -> callback.onAudioDataReceived(buffer, bytes));
}
}
audioRecord.stop();
audioRecord.release();
audioRecord = null;
}).start();
}
public void stop() {
isRecording = false;
}
public interface Callback {
void onAudioDataReceived(byte[] data, int size);
}
}
```
在此示例中,我们首先创建一个 `AudioRecord` 对象,并使用 `MediaRecorder.AudioSource.MIC` 作为录音源。然后,我们在一个新线程中读取录音数据,并调用回调函数将数据传递给主线程。最后,我们在 `stop` 方法中停止录音。
使用示例:
```java
AudioRecorder recorder = new AudioRecorder();
recorder.setCallback((data, size) -> {
// 处理录音数据
});
recorder.start();
// 录音中...
recorder.stop();
```
请注意,此示例中的 `Callback` 接口仅用于演示目的,您应该将其替换为您自己的接口,并在其中处理录音数据。另外,如果您需要将录音保存到文件中,可以使用 `AudioRecord` 的 `read` 方法读取录音数据,并将其写入文件中。
阅读全文