温馨提示×

android speechrecognizer怎样用

小樊
81
2024-11-25 18:39:58
栏目: 编程语言

要使用Android SpeechRecognizer,您需要遵循以下步骤:

  1. 添加权限:在AndroidManifest.xml文件中添加以下权限,以访问麦克风和语音识别服务。
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
  1. 检查权限:在运行时检查应用是否具有录音权限。如果没有,请请求用户授权。
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();
        }
    }
}
  1. 初始化SpeechRecognizer:在Activity中初始化SpeechRecognizer对象。
private SpeechRecognizer speechRecognizer;

private void startSpeechRecognizer() {
    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
    speechRecognizer.setRecognitionListener(new RecognitionListener() {
        // 实现RecognitionListener接口的方法
    });
}
  1. 设置意图过滤器:创建一个Intent对象,用于启动语音识别服务,并设置相应的意图过滤器。
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);
}
  1. 处理识别结果:在onActivityResult方法中处理语音识别的结果。
@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);
        // 处理识别到的文本
    }
}
  1. 开始语音识别:在需要开始语音识别的地方调用startVoiceRecognition()方法。
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        requestRecordAudioPermission();
    }
});

现在,当用户点击按钮时,应用将请求录音权限并开始语音识别。识别到的文本将显示在屏幕上。您可以根据需要处理识别到的文本。

0