简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM