【问题标题】:Android, Java only gets last word from string arrayAndroid,Java仅从字符串数组中获取最后一个单词
【发布时间】:2015-01-01 12:31:09
【问题描述】:

我已经构建了一个使用语音识别的 java 应用程序,我创建了一个这样的字符串数组:

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

现在的问题是应用只检测数组“yow”的最后一个单词,而不是“hello”或“hi”

for (String strings: greetings) 

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

所以我真的不知道我做错了什么,也许mostLikelyThingHeard 也需要一个“for”循环?

完整代码:

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();
    }
}

【问题讨论】:

  • 您是否要同时说“你好”、“嗨”、“哟”?因为在这种情况下,循环将被执行三次,并且由于 TextToSpeech.QUEUE_FLUSH,之前的话语将被清除。
  • String[] greetings = { "hallo", "hi", "yow" };“你好”在哪里?
  • 好吧,你并没有在识别一个单词后打破你的循环。如果您说“hi”并且您的程序也识别“hi”,它仍然会检查其他单词。
  • 打印你最有可能听到的东西?查看错误的确切位置
  • 您知道如何在代码中设置断点并在调试模式下运行应用程序吗?

标签: java android arrays contains


【解决方案1】:

您可以将所有单词放在一个字符串中(不是数组字符串)。我知道这不是最好的解决方案,所以我为您提供了一个简单的示例,无论您编写什么引擎都会说话。

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>

【讨论】:

  • 如果我把所有东西都放在一个字符串中,那么用户必须说那个没有用的完整字符串:(
  • 没关系。在上面的代码中,当用户说话时,文本将保存在 textview 中。最后使用 textview 文本说话。
【解决方案2】:

我看到的唯一问题是您正在检查 for 中的“doei”...除此之外,它应该可以正常工作。另外,请考虑确保听到的事情与您期望的情况相符。 此外,您应该跟踪您在 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);
    }
}

【讨论】:

  • 现在试试,谢谢! / 仍然没有检测到前两个词...只有“yow”
  • 顺便说一句,现在它甚至没有检测到任何数组的单词:(
  • 嗯,这都是关于 mostLikelyThingHeard 的内容,我们不知道你得到了什么。
  • 你做到了,男人:D 玫瑰是红紫罗兰色是蓝色 @user1961779 你让我开心,所以感谢你 xD
  • @user1961779 如何在不破坏上述脚本的情况下删除 .equals(doei))?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 2013-09-07
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多