问题
I've developed an Android App which give commands using tts (Text to Speech) and then listen to the vocal answer of the user using Speech Recognition Intent.
Obviously, only when tts finishes to speak, then the intent of speech recognition is thrown. Sometimes, mostly when I swich from an activity to another, or when I activate this process through a button, THE SPEECH RECOGNIZER INTENT STARTS BEFORE TTS FINISHES TO TALK! The problem is that the same text of the command is then acquired and analyzed instead of the words of the user. The part of the code that tells speech recognizer to wait is this one:
while(tts.isSpeaking()){
//DOING NOTHING
}
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),"Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT);
t.show();
}
Does anybody have a solution? It seems to be quite random. Sometimes it waits, sometimes not. Thanks everyone!!
回答1:
Using tts.isSpeaking()
is useless for several reasons, you can read this for details:
Problem with isSpeaking() when using Text-to-Speech on Android
Intead, you need to set OnUtteranceProgressListener
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
// Nothing
}
@Override
public void onError(String utteranceId) {
// Nothing
}
@Override
public void onDone(String utteranceId) {
// Restart recognizer here
Please note that to make this listener work you need to set TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID
with params in tts.speak call.
回答2:
Here's a sample. You might need to start speechRecognizer in the main thread for some reasons.
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
if (utteranceId.contains(<utterance_id_you_set>)){
Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
//start your recognizer here
}
};
mainHandler.post(myRunnable);
}
}
@Override
public void onError(String utteranceId) {
}
});
}
});
来源:https://stackoverflow.com/questions/24956784/speech-recognition-intent-starts-before-tts-ends-speaking