Search code examples
androidspeech-recognitiontext-to-speechspeech-to-textspeech

Greet the user on startup using speech


I want to greet the user with speech everytime they open the app.

But when i start the app, I don't hear anything.

Here's my code:

public class MainActivity extends AppCompatActivity {

TextToSpeech textToSpeech;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    textToSpeech =new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if(status==TextToSpeech.SUCCESS)
                textToSpeech.setLanguage(Locale.US);

        }
    });

    textToSpeech.speak("welcome", TextToSpeech.QUEUE_FLUSH, null,null);


}

public void onPause(){
    if(textToSpeech !=null){
        textToSpeech.stop();
        textToSpeech.shutdown();
    }
    super.onPause();
}
}

Solution

  • You should call textToSpeech.speak() after TTS is initialized, i.e. after onInit() is called. Please also check the return value and see if it's added to the queue.