16

我试图在文本到语音的开始和结束时调用一些方法,所以我使用了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方法的结尾添加了它,但是这个解决方案不是很好。与听众一起工作将是完美的。

那么我做错了什么?

4

1 回答 1

33

当您致电时,tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); 您需要向其传递带有 KEY_PARAM_UTTERANCE_ID 的地图

    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

于 2013-11-16T01:05:53.153 回答