Search code examples
androidofflinespeech

Android Offline Speech Recognition to Display Only Word


I need help with android speech-text. Is it possible to display only the first word that was detected?like when the user inputs "the cat is playing" then the text that will only appear on the text box is the word "the".

The code that I used:

protected static final int RESULT_SPEECH = 1;

private Button btn_mic;
private TextView txtText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_level1);        

    txtText = (TextView) findViewById(R.id.txt);     
    btn_mic = (Button) findViewById(R.id.mic);            

        btn_mic.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                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");

                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

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

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

                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                txtText.setText(text.get(0));
            }
            break;
        }

        }
    }

}

thanks in advance. :)


Solution

  •  ArrayList<String> text = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    
            if(text.size()>0){
                String firstOne=text.get(0);
                if(firstOne.contains(" ")){
                    String firstWord=firstOne.substring(0, firstOne.indexOf(' '));
                    txtText.setText(text.get(0));
                }else{
                    txtText.setText(text.get(0));
                }
            }