简体   繁体   English

如何在我的Android应用程序中使用内置语音识别?

[英]How to use in-built voice recognition in my Android app?

I want to use offline voice recognition in my app. 我想在我的应用中使用离线语音识别。 Setting -> “Language and Input” -> "Google Voice Typing" -> "Offline speech recognition" :- I would like to use this built-in feature. 设置->“语言和输入”->“ Google语音输入”->“离线语音识别”:-我想使用此内置功能。 In the below code, I tried to implement it using Recognizer Intent, but it uses the Google voice search (works online). 在下面的代码中,我尝试使用Recognizer Intent来实现它,但是它使用了Google语音搜索(可在线运行)。 Please help. 请帮忙。

public class MainActivity extends AppCompatActivity {

private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    promptSpeechInput();
    //onCreateOptionsMenu();
}

private void promptSpeechInput() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
    try {
        startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),
                getString(R.string.speech_not_supported),
                Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case REQ_CODE_SPEECH_INPUT: {
            if (resultCode == RESULT_OK && null != data) {

                ArrayList<String> result = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                //txtSpeechInput.setText(result.get(0));
                {
                    String a="camera";
                    if(a.compareTo(result.get(0))==0){
                        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        if (i.resolveActivity(getPackageManager()) != null) {
                            startActivityForResult(i, 1);
                        }
                    }
                }
            }
            break;
        }

    }
}

Well, here I am sending intent to camera via voice. 好吧,我在这里通过语音向相机发送意图。 So, I have a limited vocabulary requirement here. 因此,我这里的词汇量有限。

Try this: 尝试这个:

intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE,true);

Note: This will work only on API level 23 and above. 注意:这仅适用于API级别23及以上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM