Android specific words speech recognition

馋奶兔 提交于 2019-12-24 13:17:28

问题


I am trying to have the app recognize certain words said by the user using the code below, but for some reason it isn't working at all. Please review this and tell me what is wrong with it. Thank you

The app is simply suppose to display a toast message if the words "orange" or "apple" is said but nothing happens when using the code below.

//button onclick to trigger RecognizerIntent

public void OnClick_Speed_Detector(View v)
{
    Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    i.putExtra(RecognizerIntent.EXTRA_PROMPT, "speak up");
    startActivityForResult(i, 1);

}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        ArrayList<String> result = 
                data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if(((result).equals("orange")))
                {
                  Toast.makeText(getApplicationContext(), "orange", Toast.LENGTH_LONG).show();

                }   
                else
                    if (((result).equals("apple")))
                { 
                  Toast.makeText(getApplicationContext(), "apple", Toast.LENGTH_LONG).show();   
                }

    }
}

回答1:


Your issue is that you are testing if an ArrayList == a String, when it can't possibly (an ArrayList of type String contains multiple strings)

Instead of:

if ((result).equals("orange")) {}

Try:

if ((result).contains("orange")) {}

This code will look through every index of the ArrayList and determine if any of the indexes of it equal "orange". If any do then it will return

true

...and it will execute the if statement! Hope this helps!



来源:https://stackoverflow.com/questions/27209343/android-specific-words-speech-recognition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!