How to use OnUtteranceProgressListener() with TTS?

74 Views Asked by At

I want to Toast a message based on the state of TTS. For this I used OnUtteranceProgressListener() . But I didn't get the result. How can I achieve this task ?

Code given below is used to initialize TTS class.

textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
               //Check if initialisation is successful
               if(i==TextToSpeech.SUCCESS)
               {
                   //set Language
                   int result=textToSpeech.setLanguage(Locale.ENGLISH);
                    //Check if language is set successfully or not.
                   if(result==TextToSpeech.LANG_NOT_SUPPORTED||result==TextToSpeech.LANG_MISSING_DATA)
                   {
                       Toast.makeText(MainActivity.this, "Language not supported", Toast.LENGTH_SHORT).show();
                   }
                   else{
                       Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
                       textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                           @Override
                           public void onStart(String s) {
                               Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
                           }

                           @Override
                           public void onDone(String s) {
                               Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_SHORT).show();

                           }

                           @Override
                           public void onError(String s) {
                               Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
                           }
                       });
                   }

               }
               else{
                   Toast.makeText(MainActivity.this, "Initialisation failed", Toast.LENGTH_SHORT).show();
               }
            }
        });

Code given below is used to trigger the event

btnSpeak.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 speak();
             }
         });

speak() function definition:

private void speak() {
        String text="Good Morning";
        float pitch=(float)seekBarPitch.getProgress()/50;
        float speed=(float)seekBarSpeed.getProgress()/50;
        textToSpeech.setPitch(pitch);
        textToSpeech.setSpeechRate(speed);
        textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,"UTTERANCE_ID");
    }
1

There are 1 best solutions below

1
On

Toast message do not work in background thread. So we must run it on UI Thread by using runOnUIThread();