A memo when making an application using TextToSpeech on android
To get the callback, use TextToSpeech's onInit textToSpeech.setOnUtteranceProgressListener(…) I do If you do not set the utteranceId of the method that actually plays the audio, you will not receive the callback. Especially for 4 series or less, it is difficult to understand because you have to set it properly with HashMap.
tts.java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//More than lollipop
String id = String.valueOf(orderNo);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
} else {
//Below kitkat
HashMap<String, String> params = new HashMap<String, String>();
String id = String.valueOf(orderNo);
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, id);
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, params);
}
There was a difference in the behavior of onDone called when playback was finished on my terminal, and I was quite addicted to it. OnDone is called when stopped in 4 series Galaxy and 5 series Nexus. OnDone is not called when stopped in 6 series Xperia. .. .. In my case, when I stop playback with the stop button, I was having trouble controlling to set the next Text and start playback when playback was finished.
As a workaround, keep the TextToSpeech status in the enum and When the stop button is pressed, the status is changed to the stopped state. When onDone, check the status and set the next playback if stopped Corrected by setting the status to the playback state at the time of onStart callback.
tts.java
//At the time of setOnClickListener of the stop button
//ttsStatus = TTSStatusEnum.STOP;To
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
ttsStatus = TTSStatusEnum.PLAY;
}
@Override
public void onDone(String utteranceId) {
if (ttsStatus == TTSStatusEnum.STOP) {
//Already stop
return;
}
ttsStatus = TTSStatusEnum.STOP;
//Next playback process ...
}
...
UI processing that wants to change the color of the wording being played in callback You have to explicitly process it in the UI thread.
tts.java
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//Processing to make text color red
}
});
}
@Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//Processing to return the color of text
}
});
}
...
Reference: Android TTS onUtteranceCompleted callback isn't getting called
Recommended Posts