0

I'm trying to get the activity to finish after it's finished speaking but for some reason I cannot fathom it tells me that the setOnUtteranceCompleted not applicable for text to speech. I'm new to android programming so please be gentle :-)

Here's the code...

public class SpeakActivity extends Activity implements OnUtteranceCompletedListener{

    Random randnum = new Random();
    TextToSpeech tts = null;
    private boolean ttsIsInit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speak);
        // Show the Up button in the action bar.
        setupActionBar();
        startTextToSpeech();
    }

    void startTextToSpeech(){
        final int randint = randnum.nextInt(4);
        final String text = ((GlobVars) this.getApplication()).getResponse(randint);
        tts = new TextToSpeech(this, new OnInitListener() {
            public void onInit(int status) {
                tts.setOnUtteranceCompletedListener(this);
                if (status == TextToSpeech.SUCCESS) {
                    ttsIsInit = true;
                    if (tts.isLanguageAvailable(Locale.ENGLISH) >= 0){
                        tts.setLanguage(Locale.ENGLISH);
                    }
                    tts.setPitch(0.5f);
                    tts.setSpeechRate(0.5f);
                    if (tts != null && ttsIsInit) {
                        Log.d("got ere", "spoken");
                        tts.speak(text, TextToSpeech.QUEUE_ADD, null);
                    }
                }
            }
        });
    }


    // shut down tts to free the TTS resources
   @Override
   public void onDestroy() {
      if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
 }


    @Override
    public void onUtteranceCompleted(String arg0) {
        ((GlobVars) this.getApplication()).setListen(true);
        this.finish();

    }


}
IBDelta
  • 1
  • 1

1 Answers1

0

I am ot sure but as per the docs of setOnUtteranceCompletedListener(), you might need to use TextToSpeech.OnUtteranceCompletedListener listener as an argument. I think the way to use the function is as below. Note that use runOnUIThread method in case you want to make any changes to the UI on the call of the onUtteranceCompleted function.

TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
    @Override
    public void onInit(int status) {
        tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
            @Override
            public void onUtteranceCompleted(String utteranceId) {
                //Do things here
            }
        });
     }
});

Source of above : Check onUtteranceCompleted does not get called? question.

Hope this helps.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124