Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextToSpeech with API 21

Tags:

Can someone help me using TTS with API 21. All examples available are deprecated with version 21

Here's my code giving error on last line:

Calendar cal = Calendar.getInstance();                     cal.getTime();                     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");                     String text = sdf.toString();                     btn.setText("Ouvir as Horas");                      TextToSpeech tts = new TextToSpeech(NightClock.this,(TextToSpeech.OnInitListener) NightClock.this);                     tts.setLanguage(Locale.US);                     tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); 

In Android developers it says that this method is deprecated and replaced by this:

speak(String text, int queueMode, HashMap params) This method was deprecated in API level 21. As of API level 21, replaced by speak(CharSequence, int, Bundle, String).

Can someone help to code my app.

like image 562
Jose Borges Avatar asked Jan 15 '15 16:01

Jose Borges


People also ask

What is queue_ flush?

QUEUE_FLUSH. Queue mode where all entries in the playback queue (media to be played and text to be synthesized) are dropped and replaced by the new entry. int. STOPPED. Denotes a stop requested by a client.

What is AddSpeech () method in Android?

AddSpeech(String, String, Int32) Adds a mapping between a string of text and a sound resource in a package. AddSpeech(ICharSequence, String, Int32) Adds a mapping between a CharSequence (may be spanned with TtsSpans) of text and a sound resource in a package.

What is setSpeechRate float speechRate method in Android?

setPitch(float pitch)//This method sets the speech pitch for the TextToSpeech engine. setSpeechRate(float speechRate)//This method sets the speech rate. stop()//This method stop the speak.


1 Answers

I searched various site. Finally, I think I could get the answer for your Question...

Instead calling tts.speak() directly, put the following if-else statement.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {     ttsGreater21(text); } else {     ttsUnder20(text); } 

Then declare ttsGreater21() and ttsUnder20() as follows.

@SuppressWarnings("deprecation") private void ttsUnder20(String text) {     HashMap<String, String> map = new HashMap<>();     map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");     tts.speak(text, TextToSpeech.QUEUE_FLUSH, map); }  @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void ttsGreater21(String text) {     String utteranceId=this.hashCode() + "";     tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId); } 

I confirmed above code with Genymotion VM Android 5.0 and Android 4.4.4.

like image 57
xanadu6291 Avatar answered Oct 31 '22 08:10

xanadu6291