27

I try to use a TextToSpeech in my app,

String text = editText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

But the function speak(String text, int queueMode, HashMap params) is deprecated in API Level 21. Instead of that, it is adviced to use speak(CharSequence text, int queueMode, Bundle params, String utteranceId). But I don't know how to set it. Thanks

Aify
  • 3,543
  • 3
  • 24
  • 43
Francis Ngueukam
  • 994
  • 1
  • 10
  • 28

2 Answers2

60
String text = editText.getText().toString();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    tts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
} else {
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
Atif Mahmood
  • 8,882
  • 2
  • 41
  • 44
  • When I use your suggestion, Android Studio says: "params="null" utteranceId="null" and unwrap if statement suggestions. And, it didn't help enough to my case. – Bay Jan 03 '21 at 22:36
  • Build.VERSION_CODES is now obsolete (April 2021). Simply replace above conditional (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) ... etc – Albert Apr 03 '21 at 07:10
-1

Here is the complete work that work for me

Private TextToSpeech ts
 ts=new TextToSpeech(CurrentActivity.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                String text = "Any Text to Speak";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
                } else {
                    ts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
                }

            }
        });