mushahid
mushahid

Reputation: 514

Android TextToSpeech does not work if called directly from onCreate

This is a test activity when the button is pressed the textToSpeech works just fine, but it wont work when the function playString() is called, playString() is being called from the onCreate() of this TestActivity.

public class TestActivity  extends Activity {
    TextToSpeech textToSpeech;
    EditText editText;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        editText=(EditText)findViewById(R.id.editText);
        button=(Button)findViewById(R.id.button);

        textToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.UK);
                }
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sentence = "Testing String";
                textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
            }
        });
        playString();
    }

    public void playString(){
        String sentence = "Testing String";
        textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
    }

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

Upvotes: 0

Views: 436

Answers (2)

Dmitry Ikryanov
Dmitry Ikryanov

Reputation: 322

From documentation:

TextToSpeech instance can only be used to synthesize text once it has completed its initialization.

Initialization may take long time (on my device it's take ~30 seconds), so you can't use handler with some random delay.
Instead, you can place playString() in onInit block right after textToSpeech.setLanguage(Locale.UK);, so string will be played when it can be played.

Upvotes: 2

Mahesh Keshvala
Mahesh Keshvala

Reputation: 1355

Please use below code in oncreate method to call the texttospeech:

 textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                textToSpeech.setLanguage(Locale.UK);
            }
        }
    });


    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do something after 100ms

            String sentence = "Testing String";
            textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
        }
    }, 500);

Upvotes: -1

Related Questions