Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make speak block on the utterance on Android (fixes #1092) #1094

Merged
merged 6 commits into from
Oct 30, 2023
Merged
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) {
jessielw marked this conversation as resolved.
Show resolved Hide resolved
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
Loading