0

I'm having an issue using text-to-speech. I have a button which when the user clicks it will speak the words in the textview. But when I first clicked the button it didn't speak, the second time I clicked again the button it then spoke. Why is it that I need to click the button again?

here's what I've tried so far:

@Override
public void onInit(int status) { 
    if (status == TextToSpeech.SUCCESS) {
        int result = tts.setLanguage(Locale.US);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
            speakOut();
        }
    } else {
        Log.e("TTS", "Initilization Failed!");
    }
}

private void speakOut() {
    String text = tvWord.getText().toString();
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

@Override
public void onDestroy() {
    // Don't forget to shutdown tts!
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

@Override
public void onClick(View v) {
    switch(v.getId()){
    case R.id.ibSpeak:
        tts = new TextToSpeech(this, this);
        speakOut();
        break;
    case R.id.tvB:
        //Intent i = new Intent(this, )
        break;
    }
}

Any ideas? I would appreciate your help. Thanks.

2 Answers 2

1
  1. Initialize your speech engine in onCreate(), not in onClick(), so move this line:

    tts = new TextToSpeach(this, this);
    

    to onCreate()

  2. It takes some time until the engine initializes, and because you're calling speakOut() in onInit(), just wait few seconds when you start the app, if initialization is successful, you should hear the sound.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't have to create new instance of TTS Engine every time you are clicking the button so it may 'cause several problems in future. If you replace creating tts to onCreate for example the problem will be solved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.