我正在尝试结合使用RecognizerIntent
和TextToSpeech
来使手机响应用户使用RecognizerIntent
提供的某些命令。
onActivityResult
方法中的for循环检查用户对文本字符串数组的可能输入
log-cat消息会运行,但不会说出文本。
这是我的Java代码:
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TextVoice extends Activity implements OnClickListener {
static final String[] texts = { "Hello", "Welcome", "Nice to meet you" };
static final int check = 111;
ArrayList<String> results;
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.textvoice);
Button b = (Button) findViewById(R.id.bTextToVoice);
b.setOnClickListener(this);
Log.println(Log.DEBUG, "voice", "Startet");
tts = new TextToSpeech(TextVoice.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
}
}
});
}
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// Random r = new Random();
// String random = texts[r.nextInt(3)];
// tts.speak(random, TextToSpeech.QUEUE_FLUSH, null);
// }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak up, son!");
startActivityForResult(i, check);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == check && resultCode == RESULT_OK) {
results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
speak();
}
}
protected void speak() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < results.size(); i++) {
Log.println(Log.DEBUG, "voice", "Option " + i + ": " + results.get(i));
if (results.get(i).equalsIgnoreCase(texts[0])) {
Log.println(Log.DEBUG, "voice", "Registrerte: hello");
tts.speak(texts[0], TextToSpeech.QUEUE_ADD, null);
} else if (results.get(i).equalsIgnoreCase(texts[1])) {
tts.speak(texts[1], TextToSpeech.QUEUE_ADD, null);
} else if (results.get(i).equalsIgnoreCase(texts[2])) {
tts.speak(texts[2], TextToSpeech.QUEUE_ADD, null);
} else {
tts.speak("Didn't here you there", TextToSpeech.QUEUE_ADD, null);
}
}
}
@Override
protected void onPause() {
super.onPause();
if (tts != null) {
tts.stop();
tts.shutdown();
}
}
@Override
protected void onResume() {
super.onResume();
}
}
答案 0 :(得分:0)
如果你仔细观察,你的onPause()
会对你的tts产生影响,所以当你回到onActivityResult时,你的tts不再有效 - 你应该在使用之前重新初始化它。至少这看起来像是可能的原因,你应该有一些logcat bug条目甚至是异常。在UI线程上调用Thread.sleep(10000);
总是一个坏主意。