In kotlin android development how to use Android's own text to speech ?
- User
In kotlin android development how to use Android's own text to speech ?
- Assistant
To use Android's built-in Text-to-Speech (TTS) functionality in a Kotlin Android application, you'll need to integrate the
TextToSpeechclass. This class provides methods to convert text to spoken audio. Below is a step-by-step guide on how to set up and use TTS in your Kotlin app:1. Initialize TextToSpeech Object
First, you need to create an instance of the
TextToSpeechclass. This is typically done in your Activity or Fragment. Implement theTextToSpeech.OnInitListenerinterface to receive a callback when the TTS engine has finished initializing.import android.speech.tts.TextToSpeech import android.util.Log import java.util.Locale class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener { private lateinit var tts: TextToSpeech override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Initialize the TextToSpeech instance tts = TextToSpeech(this, this) } // Implement the onInit listener override fun onInit(status: Int) { if (status == TextToSpeech.SUCCESS) { // Set the language for TTS val result = tts.setLanguage(Locale.US) if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "The specified language is not supported.") } else { // TTS is successfully initialized } } else { Log.e("TTS", "Initialization failed.") } } }2. Speak Text Using TTS
After initializing, you can call the
speak()method to convert text to speech. Ensure that TTS is initialized before calling this method.private fun speakOut(text: String) { if (::tts.isInitialized) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null) } else { @Suppress("DEPRECATION") tts.speak(text, TextToSpeech.QUEUE_FLUSH, null) } } else { Log.e("TTS", "TextToSpeech not initialized") } }Usage Example:
button.setOnClickListener { val text = editText.text.toString() speakOut(text) }3. Handle TTS Lifecycle
It's important to manage the TTS engine's lifecycle by shutting it down when it's no longer needed to free up system resources.
override fun onDestroy() { // Shutdown TTS when the activity is destroyed if (::tts.isInitialized) { tts.stop() tts.shutdown() } super.onDestroy() }4. Handle Permissions (If Necessary)
While the basic TTS functionality doesn't require special permissions, if you're using features like recording or saving audio, you'll need to declare the appropriate permissions in your
AndroidManifest.xmlfile.For basic TTS, you typically don't need additional permissions.
5. Customize TTS Settings
You can customize various TTS settings, such as pitch and speech rate:
// Set pitch level tts.setPitch(1.0f) // Normal pitch tts.setPitch(0.5f) // Decrease pitch tts.setPitch(2.0f) // Increase pitch // Set speech rate tts.setSpeechRate(1.0f) // Normal speed tts.setSpeechRate(0.5f) // Slow down tts.setSpeechRate(2.0f) // Speed up6. Handling Different Locales
You can set different languages or locales depending on your needs:
tts.setLanguage(Locale.UK) tts.setLanguage(Locale("es", "ES")) // Spanish (Spain) tts.setLanguage(Locale("fr", "FR")) // French (France)Always check if the language is supported:
val result = tts.setLanguage(Locale("es", "ES")) if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "The specified language is not supported.") }7. Full Example
Putting it all together, here's a comprehensive example:
import android.os.Build import android.os.Bundle import android.speech.tts.TextToSpeech import android.util.Log import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.util.Locale class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener { private lateinit var tts: TextToSpeech private var isTtsInitialized = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize TextToSpeech tts = TextToSpeech(this, this) // Set up button click listener buttonSpeak.setOnClickListener { val text = editText.text.toString() speakOut(text) } } // TextToSpeech.OnInitListener implementation override fun onInit(status: Int) { if (status == TextToSpeech.SUCCESS) { // Set language val result = tts.setLanguage(Locale.US) isTtsInitialized = result != TextToSpeech.LANG_MISSING_DATA && result != TextToSpeech.LANG_NOT_SUPPORTED if (!isTtsInitialized) { Log.e("TTS", "The specified language is not supported.") } } else { Log.e("TTS", "Initialization failed.") } } private fun speakOut(text: String) { if (isTtsInitialized) { // Optional: Set pitch and speech rate tts.setPitch(1.0f) tts.setSpeechRate(1.0f) // Speak the text if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null) } else { @Suppress("DEPRECATION") tts.speak(text, TextToSpeech.QUEUE_FLUSH, null) } } else { Log.e("TTS", "TextToSpeech not initialized or language not supported.") } } override fun onDestroy() { // Shutdown TextToSpeech if (::tts.isInitialized) { tts.stop() tts.shutdown() } super.onDestroy() } }XML Layout (
activity_main.xml):<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:padding="16dp"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter text to speak" /> <Button android:id="@+id/buttonSpeak" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Speak" /> </LinearLayout>Notes:
- Lifecycle Management: Always shut down the TTS engine in the
onDestroy()method to prevent memory leaks. - Threading: TTS initialization and speaking methods should run on the main thread.
- Error Handling: Implement proper error handling for cases where the language is not supported or initialization fails.
- Asynchronous Initialization: TTS engine initialization is asynchronous. Ensure that you don't call
speak()before theonInit()callback indicates success.
Additional Features
-
Utterance Progress Listener: You can monitor the progress of speech by setting an
UtteranceProgressListener.tts.setOnUtteranceProgressListener(object : UtteranceProgressListener() { override fun onStart(utteranceId: String) { // Called when TTS starts speaking } override fun onDone(utteranceId: String) { // Called when TTS has finished speaking } override fun onError(utteranceId: String) { // Called if an error occurred } }) -
Saving Audio to File: If you need to save the spoken audio to a file, use the
synthesizeToFile()method.val file = File(filesDir, "tts_output.wav") val params = Bundle() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts.synthesizeToFile(text, params, file, "ttsOutput") } else { @Suppress("DEPRECATION") tts.synthesizeToFile(text, hashMapOf(), file.absolutePath) }
Conclusion
By following the steps above, you can effectively integrate Android's built-in Text-to-Speech functionality into your Kotlin Android application. This allows your app to convert text input into audible speech, enhancing user interaction and accessibility.
- Lifecycle Management: Always shut down the TTS engine in the