Search code examples
androidtext-to-speech

Why my onRangeStart() method of text to speech is not executing?


I am working on a text to speech application, text to speech is working fine but now I want to highlight each word while it is being spoken by the speech to text engine.

However, I have overridden onRangeStart() method, but actually, it is not executing in my device(API-25) and below.

Text to Speech is working fine in all devices but the text is highlighted (while TTS processing) only in 26+ API devices. Why this is happing and how to make this functionality backwards compatible? here is my code.

Implemented OnInitListener()

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {...

**Here is onInit(){...}

 @Override
public void onInit(int i) {
    if (i == TextToSpeech.SUCCESS) {
        int result = mTTS.setLanguage(Locale.ENGLISH);

        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "Language not supported");
        } else {
            mButtonSpeak.setEnabled(true);
        }
    } else {
        Log.e("TTS", "Initialization failed");
    }
    mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
        @Override
        public void onStart(String s) { Log.d("TTS", "onStart: "+s); }

        @Override
        public void onDone(String s) { Log.d("TTS", "onDone: "); }

        @Override
        public void onError(String s) { Log.d("TTS", "onError: "); }


        @Override
        public void onRangeStart(String utteranceId, final int start, final int end, int frame) {
            super.onRangeStart(utteranceId, start, end, frame);
            Log.d(TAG, "onRangeStart: ");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Spannable coloredText = new SpannableString(mTextParagraph.getText());
                    coloredText.setSpan(new ForegroundColorSpan(Color.GREEN),
                            start,
                            end,
                            Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    mTextParagraph.setText(coloredText);
                    Log.d(TAG, "Color: ");
                }
            });
        }
    });
}

Solution

  • It's because onRangeStart was added in API 26. Therefore, unfortunately, it doesn't work on API 25.