简体   繁体   中英

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. In the below code, I tried to implement it using Recognizer Intent, but it uses the Google voice search (works online). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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