UtteranceProgressListener未调用

时间:2018-01-14 15:01:48

标签: java android callback text-to-speech onutterancecompleted

我正在尝试在Android应用中的TextToSpeech对象完成一个句子后执行某些操作,但我的UtteranceProgressListener.onDone()方法从未被调用过。我尝试了很多东西,包括来自this post的建议,但没有任何效果。我的应用程序的相关代码发布在下面。 TextToSpeech对象正确地说出了我给它的句子,但UtteranceProgressListener中没有调用回调函数。有人可以帮我辨别出什么问题吗?例如,我提供给TextToSpeech.speak()函数的话语ID是否需要采用我遗漏的某种特殊格式?

mtts = new TextToSpeech(myAct, new TextToSpeech.OnInitListener() {
    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            mtts.setLanguage(Locale.US);
        }
    }
});

mtts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
    @Override
    public void onDone(String utteranceId) {
        Toast.makeText(myAct, "OnDone called", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onError(String utteranceId) {
        Toast.makeText(myAct, "OnError called", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(String utteranceId) {
        Toast.makeText(myAct, "OnStart called", Toast.LENGTH_LONG).show();
    }
});

Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
myAct.mtts.speak(myText, TextToSpeech.QUEUE_FLUSH, params, "MyID");

1 个答案:

答案 0 :(得分:0)

看看logcat,您的代码可能已触发: android.view.ViewRootImpl $ CalledFromWrongThreadException

如果要执行一些GUI线程操作,请使用处理程序和可运行的程序,如下所示:

public void onDone(String utteranceId) {
  Log.v(TAG, "Speaking done"); // this is OK
  // This is GUI-thread part
  final View v = findViewById(R.id.txtStatus);
  v.getHandler().post(new Runnable() {
    @Override
    public void run() {
      txtStatus.setText("Speaking done");
    }
  });
}

并开始讲TTS:

tts.speak("bla bla bla", TextToSpeech.QUEUE_FLUSH, null, "1");