为什么 UtteranceProgress Listener 没有被文本转语音调用?

2022-09-03 04:44:48

我试图在文本到语音的开头和结尾调用一些方法,所以我使用了,但它不起作用/被调用。setOnUtteranceProgressListener

我做错了什么?

以下是所需的代码:

类:

public class SpeechRecognizerActivity extends Activity implements TextToSpeech.OnInitListener

初始化方法:

 @Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        String language = Locale.getDefault().getLanguage();
        int result = tts.setLanguage(Locale.US);
        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
           
        }
    } else {
        Log.e("TTS", "Initilization Failed!");
    }
}

开始说话的方法:

private void speakOut(String text) {
    setTtsListener();
    tts.setPitch(1.5f);
    tts.setSpeechRate(1.5f);
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

监听器(方法在 speakOut 中被调用):这些日志都不会显示在 Logcat 中。

private void setTtsListener() {
    if (Build.VERSION.SDK_INT >= 15)
    {
        int listenerResult = tts.setOnUtteranceProgressListener(new UtteranceProgressListener()
        {
            @Override
            public void onDone(String utteranceId)
            {
                Log.d(TAG,"progress on Done " + utteranceId);
            }

            @Override
            public void onError(String utteranceId)
            {
                Log.d(TAG,"progress on Error " + utteranceId);
            }

            @Override
            public void onStart(String utteranceId)
            {
                Log.d(TAG,"progress on Start " + utteranceId);
            }
        });
        if (listenerResult != TextToSpeech.SUCCESS)
        {
            Log.e(TAG, "failed to add utterance progress listener");
        }
    }
    else
    {
        int listenerResult = tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener()
        {
            @Override
            public void onUtteranceCompleted(String utteranceId)
            {
                Log.d(TAG,"progress on Completed " + utteranceId);
            }
        });
        if (listenerResult != TextToSpeech.SUCCESS)
        {
            Log.e(TAG, "failed to add utterance completed listener");
        }
    }
}

我发现的一个小解决方法是这样的:

boolean speakingEnd = tts.isSpeaking();
    do {
        speakingEnd = tts.isSpeaking();
    } while ((speakingEnd));
    Log.d(TAG,"talking stopped");

我已经在方法的末尾添加了它,但是这个解决方案不是很好。与听众一起工作将是完美的。speakOut

那么我做错了什么呢?


答案 1

当您致电时,您需要向其传递一张带有KEY_PARAM_UTTERANCE_IDtts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    HashMap<String, String> map = new HashMap<String, String>();
    map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"messageID");
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);

这让TextToSpeech知道使用你的话语监听器。text


答案 2

推荐