How to do Text-to-speech the easy way with Android / Kotlin / Compose (2024)

Serge Hulne
2 min readApr 8, 2024

--

Here is the code snippet:

Just create a new empty Kotlin project in Android Studio (empty activity):

Android Studio project creation

If the name of your project is, e.g. MyTest, just replace tts4 with "mytest" (or whatever the name of your project is) on the first line of the following snippet:

package com.example.tts4 // Modify this line to match your package name

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.*
import android.speech.tts.TextToSpeech
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import java.util.Locale


class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TextToSpeechScreen()
}
}
}

val sentences = listOf(
"Good morning, Captain",
"Do you need another mule skinner",
"Out on your new road line",
)

@Composable
fun TextToSpeechScreen() {
var isSpeaking by remember { mutableStateOf(false) }
val tts = rememberTextToSpeech()

Column(modifier = Modifier.padding(24.dp)) {
isSpeaking = false
for (sentence in sentences) {
Button(onClick = {
if (tts.value?.isSpeaking == true) {
tts.value?.stop()
isSpeaking = false
} else {
tts.value?.speak(
sentence, TextToSpeech.QUEUE_FLUSH, null, ""
)
isSpeaking = true
}
}) {
Text(sentence)
} // End Button
} // End for

}
}

@Composable
fun rememberTextToSpeech(): MutableState<TextToSpeech?> {
val context = LocalContext.current
val tts = remember { mutableStateOf<TextToSpeech?>(null) }
DisposableEffect(context) {
val textToSpeech = TextToSpeech(context) { status ->
if (status == TextToSpeech.SUCCESS) {
tts.value?.language = Locale.US
}
}
tts.value = textToSpeech

onDispose {
textToSpeech.stop()
textToSpeech.shutdown()
}
}
return tts
}

--

--

Serge Hulne
Serge Hulne

Written by Serge Hulne

Author, scientist (Physics PhD), philosophy, Sci-Fi, thrillers, humor, blues and Irish music, green energy, origins of consciousness.

No responses yet