0
votes

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.

1
Use the 'prefer offline' extra - developer.android.com/reference/android/speech/…brandall
Thanks for replying. It didn't work though.HG9
What part of it failed?brandall
The Google voice recognition which opens still asks for Internet. Does not work offline. I had added the line..intent.putExtra (Recognizer.EXTRA_PREFER_OFFLINE,true);HG9
Have you been through every step of this answer stackoverflow.com/a/17674655/1256219brandall

1 Answers

1
votes

Try this:

intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE,true);

Note: This will work only on API level 23 and above.