要配置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. Could not use speech recognition.", Toast.LENGTH_SHORT).show();
}
}
}
在onCreate()方法中调用requestRecordAudioPermission():
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestRecordAudioPermission();
}
private SpeechRecognizer speechRecognizer;
private Intent speechRecognizerIntent;
private void startSpeechRecognizer() {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
}
SpeechRecognizer.OnResultsListener
接口的类,并在其中处理识别结果。private class SpeechRecognizerListener implements SpeechRecognizer.OnResultsListener {
@Override
public void onResults(Bundle results) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null && !matches.isEmpty()) {
String recognizedText = matches.get(0);
Toast.makeText(MainActivity.this, "Recognized: " + recognizedText, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(int error) {
Toast.makeText(MainActivity.this, "Error: " + error, Toast.LENGTH_SHORT).show();
}
}
speechRecognizer.setRecognitionListener(new SpeechRecognizerListener());
speechRecognizer.startListening(speechRecognizerIntent);
现在,您已经配置了Android SpeechRecognizer。当用户说话时,它将识别并显示所说的内容。