Android 文字转语音 - 突出显示所说的词

Android Text To Speech - Highlight spoken words

在我的 UtteranceProgressListener 中,我覆盖了 onRangeStart 但它没有被调用。

       @Override
        public void onRangeStart(String utteranceId, int start, int end, int frame) {
            super.onRangeStart(utteranceId, start, end, frame);

            Spannable wordToSpan = new SpannableString(smartOcrDisplayTextLeft.getText());
            wordToSpan.setSpan(new ForegroundColorSpan(Color.GREEN), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

            smartOcrDisplayTextLeft.setText(wordToSpan);

        }

好的,代码是正确的。从设置 -> 辅助功能到您需要 select Google 作为文本到语音引擎。

根据 UtteranceProgressListener docs、"The callbacks specified in this method can be called from multiple threads."

要验证这一点,您可以添加

boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
                Log.i("XXX", "was onRangeStart() called on a background thread? : " + wasCalledFromBackgroundThread);

到 onRangeStart() 方法主体。

根据我的经验,它们经常在后台线程中被调用。

所以,像这样包围 UI 操作会更安全:

runOnUiThread(new Runnable() {
    @Override
    public void run() {

        Spannable wordToSpan = new SpannableString(smartOcrDisplayTextLeft.getText());
        wordToSpan.setSpan(new ForegroundColorSpan(Color.GREEN), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        smartOcrDisplayTextLeft.setText(wordToSpan);

    }
 });