Skip to content

Instantly share code, notes, and snippets.

@guhungry
Created April 5, 2019 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guhungry/1bf33f226c190bfd5fd79b2e4eb392eb to your computer and use it in GitHub Desktop.
Save guhungry/1bf33f226c190bfd5fd79b2e4eb392eb to your computer and use it in GitHub Desktop.
TextToSpeech api wrapper
package com.accenture.acncodechallengeandroid.utils;
import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import java.lang.ref.WeakReference;
/**
* Text to Speech Utilities Class
* Wrapper of TextToSpeech api
*/
public class TalkUtils extends UtteranceProgressListener implements TextToSpeech.OnInitListener {
private static TalkUtils instance;
private WeakReference<Context> context;
private String text;
private TextToSpeech engine = null;
private boolean isRunning = false;
private int count = 0;
private TalkUtils(Context context) {
this.context = new WeakReference<>(context);
}
/**
* Shared Instance
* @param context Application context so it won't leaks
* @return TextUtils instance
*/
public static TalkUtils getInstance(Context context) {
if (instance == null) {
instance = new TalkUtils(context);
}
return instance;
}
public void talk(String text) {
this.text = text;
if (ensureTalkEngineReady()) startTalk();
}
private boolean ensureTalkEngineReady() {
if (engine != null && isRunning) return true;
Context context = this.context.get();
if (context == null) return false;
count = 0;
engine = new TextToSpeech(context, this);
engine.setOnUtteranceProgressListener(this);
isRunning = true;
return false;
}
private void startTalk() {
count++;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
engine.speak(text, TextToSpeech.QUEUE_ADD, null, "");
} else {
engine.speak(text, TextToSpeech.QUEUE_ADD, null);
}
text = null;
}
private void clear() {
count--;
if (count > 0) return;
engine.shutdown();
engine = null;
isRunning = false;
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) startTalk();
}
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
clear();
}
@Override
public void onError(String utteranceId) {
clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment