android studio获取mic
时间: 2023-09-06 17:14:10 浏览: 278
要在Android Studio中获取麦克风(mic)的输入,你可以使用Android的AudioRecord类。以下是一个示例代码片段,用于获取设备的麦克风音频输入:
```java
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
public class MainActivity extends AppCompatActivity {
private static final int RECORDER_SAMPLE_RATE = 44100; // 采样率
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO; // 单声道
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; // 16位PCM编码
private AudioRecord audioRecord;
private boolean isRecording = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化AudioRecord对象
int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLE_RATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLE_RATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
// 开始录制
startRecording();
}
private void startRecording() {
isRecording = true;
audioRecord.startRecording();
// 开启一个线程读取录制的音频数据
new Thread(new Runnable() {
@Override
public void run() {
byte[] buffer = new byte[bufferSize];
while (isRecording) {
int bytesRead = audioRecord.read(buffer, 0, bufferSize);
// 处理读取到的音频数据
}
}
}).start();
}
private void stopRecording() {
isRecording = false;
audioRecord.stop();
audioRecord.release();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopRecording();
}
}
```
这段代码会在应用启动时初始化`AudioRecord`对象,并在单独的线程中持续读取麦克风输入的音频数据。你可以在`while`循环中处理读取到的音频数据,例如进行声音分析、录制等操作。记得在应用销毁时停止录制并释放资源。
阅读全文