Did you perhaps mean that:
- reading starts -> Play is gone and Stop is visible
- reading ends -> Play is visible, Stop is gone
Anyway, the purpose of UtteranceProgressListener
is exactly what you are describing. It's used to monitor the progress of the speech synthesis.
You can add an "utterance id" (here "helloText") to any text that is spoken out:
tts.speak("Hello Stack Overflow!", TextToSpeech.QUEUE_ADD, "helloText");
But that's not really necessary in your case, so the last parameter can be null:
tts.speak("Hello Stack Overflow!", TextToSpeech.QUEUE_ADD, null);
The UtteranceProgressListener
should be added before calling speak()
. You could do that for example in the TTS initialization callback onInit()
if the TTS status is TextToSpeech.SUCCESS
.
It can be a separate class or just an anonymous inner class:
speech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
// Speaking started.
}
@Override
public void onDone(String utteranceId) {
// Speaking stopped.
}
}
@Override
public void onError(String utteranceId) {
// There was an error.
}
});
The onStart()
method is triggered when speaking starts (soon after calling speak()
) so that's one possible place to switch the visible button. For example the Play button could be switched to a Stop button.
The onDone()
method is triggered when speaking is finished and it's another possible place to switch the visible button. For example the Stop button could be switched to a Play button.
And as you can see the "utterance id" is available in both methods if you provided a one in the speak()
method call. It would be useful if you needed to know exactly which text is being spoken/finished being spoken/failed with an error.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…