简体   繁体   English

Android,Java仅从字符串数组获取最后一个单词

[英]Android, Java only gets last word from string array

I have build a java app which use voice recognition, I created a string array like this: 我已经建立了一个使用语音识别的Java应用程序,我创建了一个字符串数组,如下所示:

String[] greetings = {"hello", "hi", "yow"};

Now the problem is is that the app is only detecting the last word of the array "yow", not "hello" or "hi" 现在的问题是,应用程序仅检测到数组“ yow”的最后一个单词,而不是“ hello”或“ hi”

for (String strings: greetings) 

                 { if (mostLikelyThingHeard.contains(strings)) {
                            tts.speak("Hey nice to see you!",
                                    TextToSpeech.QUEUE_FLUSH, null);

So I really don't know what I am doing wrong, maybe mostLikelyThingHeard needs a 'for' loop also? 所以我真的不知道我在做什么错,也许mostLikelyThingHeard需要一个“ for”循环?

Full code: 完整代码:

package nl.giovanniterlingen.pws;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity implements OnInitListener {
    private static final String TAG = "PWS";

    private TextView result;

    private TextToSpeech tts;

    private Button speak;

    private int SPEECH_REQUEST_CODE = 1234;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        speak = (Button) findViewById(R.id.bt_speak);
        speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRecognizeIntent();
            }
        });

        speak.setEnabled(false);
        result = (TextView) findViewById(R.id.tv_result);

        tts = new TextToSpeech(this, this);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            speak.setEnabled(true);
        } else {
            // failed to init
            finish();
        }

    }

    private void sendRecognizeIntent() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Aan het luisteren...");
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100);
        startActivityForResult(intent, SPEECH_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SPEECH_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> matches = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (matches.size() == 0) {
                    tts.speak("Ik heb niks gehoord, probeer het nog eens",
                            TextToSpeech.QUEUE_FLUSH, null);
                } else {
                    String mostLikelyThingHeard = matches.get(0);
                    result.setText("Dit heeft u gezegd: "
                            + mostLikelyThingHeard + ".");
                    String doei = "doei";
                    String[] greetings = { "hello", "hi", "yow" };

                    for (String strings : greetings) {

                        if (mostLikelyThingHeard.contains(strings)) {
                            tts.speak("Hey nice to see you!",
                                    TextToSpeech.QUEUE_FLUSH, null);

                        } else if (mostLikelyThingHeard.equals(doei)) {
                            tts.speak("Okay tot de volgende keer!",
                                    TextToSpeech.QUEUE_FLUSH, null);
                        } else {
                            tts.speak("Ik begrijp niet wat je bedoeld met "
                                    + mostLikelyThingHeard
                                    + " probeer het anders te verwoorden.",
                                    TextToSpeech.QUEUE_FLUSH, null);
                        }
                    }
                }
            } else {
                Log.d(TAG, "result NOT ok");
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (tts != null) {
            tts.shutdown();
        }
        super.onDestroy();
    }
}

You can take all words in a single string (not array string).I know that's would not be the best solution so I am providing you a simple example in which whatever you write the engine will speak. 您可以将所有单词放在一个字符串(而不是数组字符串)中。我知道这不是最好的解决方案,因此,我为您提供了一个简单的示例,其中无论您编写什么引擎都可以说话。

MainActivity.java
package com.authorwjf.talk2me;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    protected static final int REQUEST_OK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
    }


}
//The on click handler is responsible for firing off the voice intent. 

@Override
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
         i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
             try {
             startActivityForResult(i, REQUEST_OK);
         } catch (Exception e) {
                Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
         }
}

//When the intent calls back, we display the transcribed text.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_OK  && resultCode==RESULT_OK) {
                ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                ((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));
        }
    }

//activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="132dp"
        android:text="..." ></TextView>

    <ImageButton
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text1"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:layout_marginTop="37dp"
        android:src="@android:drawable/ic_btn_speak_now" ></ImageButton>

</RelativeLayout>

the only problem I am seeing is that you're checking for "doei" inside the for... Besides that, it should work ok. 我看到的唯一问题是,您正在for中检查“ doei”。除此之外,它应该可以正常工作。 also, consider ensuring the thing heard is in the case you're expecting it to be. 另外,请考虑确保听到的声音符合您的预期。 Also, you should keep track of the fact that you found a word or not in the for. 另外,您应跟踪for中是否找到单词的事实。

String doei = "doei";
String[] greetings = { "hallo", "hi", "yow" };
mostLikelyThingHeard = mostLikelyThingHeard.toLowerCase();
boolean found = false;

for (String strings : greetings) {
    if (mostLikelyThingHeard.contains(strings)) {
        tts.speak("Hey nice to see you!",
            TextToSpeech.QUEUE_FLUSH, null);
        found = true;
        break;
    }
} 
if (!found) { 
    if (mostLikelyThingHeard.equals(doei)) {
        tts.speak("Okay tot de volgende keer!", TextToSpeech.QUEUE_FLUSH, null);
    } else {
        tts.speak("Ik begrijp niet wat je bedoeld met "
          + mostLikelyThingHeard
          + " probeer het anders te verwoorden.",
          TextToSpeech.QUEUE_FLUSH, null);
    }
}

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

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