Skip to content

Commit

Permalink
feat: Make speak block on the utterance on Android (fixes #1092) (#1094)
Browse files Browse the repository at this point in the history
* feat: Make speak block on the utterance on Android (fixes #1092)

* refactor: generated a random UUID() instead of a hardcoded string
refactor: return result.success(true) onDone method

* fix: compile error due to missing imports and args

* fix: speak method was not being properly called in method handler above

* fix: properly call the speak method
  • Loading branch information
jessielw authored Oct 30, 2023
1 parent 5abc3fc commit 49ec0a0
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions android/app/src/main/kotlin/com/rtirl/chat/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context
import android.content.Intent
import android.net.Uri
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.os.Build
import android.provider.Settings
import androidx.annotation.NonNull
Expand All @@ -13,6 +14,7 @@ import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.UUID


class MainActivity : FlutterActivity() {
Expand Down Expand Up @@ -86,8 +88,7 @@ class TextToSpeechPlugin(context: Context) : MethodCallHandler {
"speak" -> {
val text = call.argument<String>("text")
if (!text.isNullOrBlank()) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null)
result.success(true)
speak(text, result)
} else {
result.error("INVALID_ARGUMENT", "Text is empty or null", null)
}
Expand All @@ -100,9 +101,28 @@ class TextToSpeechPlugin(context: Context) : MethodCallHandler {
}
}

fun speak(text: String) {
fun speak(text: String, result: Result) {
if (!text.isNullOrBlank()) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null)
val utteranceId = UUID.randomUUID().toString()
tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onStart(utteranceId: String) {
// Speech has started
}

override fun onDone(utteranceId: String) {
result.success(true)
}

override fun onError(utteranceId: String) {
// Speech encountered an error
// Handle errors as needed
}
})

// Speak with the specified utteranceId
val params = HashMap<String, String>()
params[TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID] = utteranceId
tts.speak(text, TextToSpeech.QUEUE_FLUSH, params)
}
}

Expand Down

0 comments on commit 49ec0a0

Please sign in to comment.