UtteranceProgressListener不会调用这些函数

时间:2016-05-14 19:21:53

标签: java android text-to-speech

我正在努力制作一款支持语音的应用程序,但是我遇到了一个重大问题。

无论我在何处放置Speak方法,我的UtteranceProgressListener类都不会调用任何给定的方法。

这是我的代码:

这是我的OnCreate方法:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    voiceBtn = (Button) findViewById(R.id.startListeningBtn);

    voiceBtn.setEnabled(false);
    textToSpeech = new TextToSpeech(mContext,new botListener());

  }    

这是OnInitListner Imeplementation

public class botListener implements TextToSpeech.OnInitListener{
    @Override
    public void onInit(int i) {

        if(i == TextToSpeech.SUCCESS)
        {
            int s = textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String s) {
                Toast.makeText(getApplicationContext(),"Done Speaking",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDone(String s) {
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(String s) {
                Toast.makeText(getApplicationContext(),"Done Speaking",Toast.LENGTH_SHORT).show();
            }
        });
        Log.d(TAG,String.valueOf(s));

            int result = textToSpeech.setLanguage(Locale.ENGLISH);

            if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
                Log.e(TAG,"Language not supported");
                Intent installLanguage = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installLanguage);
            }
            Log.d(TAG,"Started Voice Speaker");
        }
        else{
            Log.e(TAG,"initialization failed");
        }
    }
}

现在,当我按下按钮时,发生的事件是:

public void initVoiceRecog(View v){
    //Toast.makeText(mContext,"Clicked",Toast.LENGTH_SHORT).show();
    Speak("hello","1");
    // does some other things here after that 

}

private void Speak(String text,String identifierID){

    if(Build.VERSION.SDK_INT>21) {
        Bundle params = new Bundle();
        params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,identifierID);
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, params, identifierID);
    }
    else{
    // ttsMap is a HashMap
    ttsMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,identifierID);
    textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,ttsMap );
    }
}

我的问题是,在打招呼之后,它不会触发OnStart()OnError()OnDone()方法。为什么会这样?

我尝试使用已弃用的setOnUtteranceListner(),同样的结果。它没有触发任何方法,Toast不会出现。

请告诉我们修复或解决方法。

我试过的设备是:

  • API 19 Micromax Canvas Nitro
  • API 21 Samsung S4
  • API 23(Marshmellow)ASUS Zenfone
  • 1 个答案:

    答案 0 :(得分:3)

    我终于弄明白为什么回调不起作用。事实证明,他们正在工作并呼吁一个单独的线程。因此,要执行正常功能,请调用' Activity.this.RunOnUiThread'把它放在回调函数中。