Skip to content

Instantly share code, notes, and snippets.

@pksokolowski
Last active March 2, 2020 20:31
Show Gist options
  • Save pksokolowski/e64531e62ca5451ce04536216205e3c2 to your computer and use it in GitHub Desktop.
Save pksokolowski/e64531e62ca5451ce04536216205e3c2 to your computer and use it in GitHub Desktop.
A very simple class utilizing TTS engine on an Android phone to say something out loud.
/**
* Utilizes TextToSpeech engine on the device to speak out loud what you want it to say.
*/
@PerApp
class Voice @Inject constructor(
private val context: Application
) {
private var isTtsReady = false
private var tts: TextToSpeech? = null
private var postponedTextToSay: String? = null
/**
* Call this in order to prepare TextToSpeech engine.
*/
fun prepareTts() {
if (isTtsReady) return
tts = TextToSpeech(context, OnInitListener { status ->
if (tts!!.setLanguage(Locale.getDefault()) == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
if (status == TextToSpeech.SUCCESS) {
isTtsReady = true
postponedTextToSay?.let {
say(it)
postponedTextToSay = ""
}
}
}
})
}
fun say(text: String) {
if (isTtsReady) {
tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "Unique Utterance ID")
} else {
postponedTextToSay = text
}
}
/**
* Release non-managed resources. Call this once you're done using the Voice.
*/
fun release() {
tts?.shutdown()
isTtsReady = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment