51 lines
1.7 KiB
Kotlin
51 lines
1.7 KiB
Kotlin
package dev.mygo
|
|||
|
|
|
||
|
|
import android.speech.tts.TextToSpeech
|
||
|
|
import org.json.JSONObject
|
||
|
|
import java.util.Locale
|
||
|
|
|
||
|
|
class TTSPlugin : MyGoPlugin {
|
||
|
|
private var engine: TextToSpeech? = null
|
||
|
|
private var ready = false
|
||
|
|
private var pending: Pair<String, PluginReply>? = null
|
||
|
|
|
||
|
|
override fun call(method: String, args: JSONObject, reply: PluginReply) {
|
||
|
|
when (method) {
|
||
|
|
"speak" -> {
|
||
|
|
val text = args.optString("text").ifEmpty { return reply.failure(PluginFailure("Empty", "no text")) }
|
||
|
|
if (ready) {
|
||
|
|
engine?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
|
||
|
|
reply.success(null)
|
||
|
|
} else {
|
||
|
|
pending = text to reply
|
||
|
|
init()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
"stop" -> {
|
||
|
|
engine?.stop()
|
||
|
|
reply.success(null)
|
||
|
|
}
|
||
|
|
else -> reply.failure(PluginFailure("NoMethod", method))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private fun init() {
|
||
|
|
if (engine != null) return
|
||
|
|
engine = TextToSpeech(PluginHost.context) { status ->
|
||
|
|
if (status == TextToSpeech.SUCCESS) {
|
||
|
|
engine?.setLanguage(Locale.getDefault())
|
||
|
|
ready = true
|
||
|
|
val p = pending
|
||
|
|
pending = null
|
||
|
|
if (p != null) {
|
||
|
|
engine?.speak(p.first, TextToSpeech.QUEUE_FLUSH, null, "openchamber")
|
||
|
|
p.second.success(null)
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
val p = pending
|
||
|
|
pending = null
|
||
|
|
if (p != null) p.second.failure(PluginFailure("Init", "text-to-speech is unavailable"))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|