要使用Android SpeechRecognizer,您需要遵循以下步骤:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private void requestRecordAudioPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_AUDIO_PERMISSION);
} else {
startSpeechRecognizer();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startSpeechRecognizer();
} else {
Toast.makeText(this, "Permission denied. Can't use speech recognition.", Toast.LENGTH_SHORT).show();
}
}
}
private SpeechRecognizer speechRecognizer;
private void startSpeechRecognizer() {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
// 实现RecognitionListener接口的方法
});
}
private static final int START_SPEECH_RECOGNITION = 1;
private void startVoiceRecognition() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak now");
startActivityForResult(intent, START_SPEECH_RECOGNITION);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == START_SPEECH_RECOGNITION && resultCode == RESULT_OK && data != null) {
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String recognizedText = results.get(0);
// 处理识别到的文本
}
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestRecordAudioPermission();
}
});
现在,当用户点击按钮时,应用将请求录音权限并开始语音识别。识别到的文本将显示在屏幕上。您可以根据需要处理识别到的文本。