Search code examples
javaandroidtext-to-speech

TextToSpeech.stop() is not working


I am calling text to speech speak() continously in onUteranceComplete() method, when an event occurs. The speak method is working fine and it is continously speaking the text but I am facing a weird problem in this code. When the event finishes, I call textToSpeech.stop() method, but the speak method keeps speaking and it seems like stop() isn't working at all. I guess the problem is occuring because of calling speak() continously in onUteranceCOmplete().

What do you experts think, what is the cause of this problem?

        @Override
        public void onInit(int status) {

            if(status != TextToSpeech.ERROR)
            {
                Toast.makeText(getApplicationContext(), "text to speech created", Toast.LENGTH_SHORT).show();
                tts.setLanguage(Locale.US);
                tts.setPitch(1.2f);
                tts.setSpeechRate(1.0f);

                tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

                    @Override
                    public void onUtteranceCompleted(String arg0) {
                        // TODO Auto-generated method stub

                        tts.speak("hello world", TextToSpeech.QUEUE_FLUSH, hash);

                    }
                });
            }

    @Override
    public void onCallStateChanged(int state, final String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);
       ....
       x = tts.speak("hello world", TextToSpeech.QUEUE_FLUSH, hash);
   }

Regards


Solution

  • You should set a class member flag

    private boolean mShouldSpeak = true;  
    

    and then check the flag in onUtteranceCompleted

    tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
    
                    @Override
                    public void onUtteranceCompleted(String arg0) {
                        // TODO Auto-generated method stub
                        if (mShouldSpeak) 
                        {
                            tts.speak("hello world", TextToSpeech.QUEUE_FLUSH, hash);
                        }
    
                    }
                });
    

    When the event finished just set mShouldSpeak to false