Overview
TheTextToSpeechController class provides a simplified interface for converting text to speech using Android’s TextToSpeech engine. It is configured for Spanish (Chile) locale and handles initialization automatically.
Location: com.demodogo.ev_sum_2.services.TextToSpeechController
Constructor
The Android application context required for initializing the TextToSpeech engine
Initialization
The controller automatically initializes the TextToSpeech engine on creation:- Language: Set to Spanish (Chile) -
"es-CL" - Readiness: Tracked internally to ensure the engine is ready before speaking
- Queue Mode: Uses
QUEUE_FLUSHto replace any ongoing speech
Methods
speak
Converts the provided text to speech.The text to speak. Will be trimmed before processing.
The method performs automatic validation:
- Returns silently if the TTS engine is not ready
- Returns silently if the text is blank after trimming
- Uses
QUEUE_FLUSHmode, which stops any ongoing speech before starting new speech
Usage Example
stop
Stops any ongoing speech immediately.This method interrupts and clears any speech currently being spoken.
Usage Example
destroy
Releases all resources used by the TextToSpeech engine.- Stops any ongoing speech
- Shuts down the TTS engine
- Nullifies the engine reference
Usage Example
Properties
The controller maintains internal state:- tts:
TextToSpeech?- The underlying TTS engine instance - ready:
Boolean- Indicates whether the engine is initialized and ready
These properties are private and managed automatically. The
ready flag ensures that speak() only works when the engine is properly initialized.Speech Configuration
The controller uses these settings:| Setting | Value | Description |
|---|---|---|
| Language | es-CL | Spanish (Chile) |
| Queue Mode | QUEUE_FLUSH | Replaces ongoing speech |
| Utterance ID | "phrase_tts" | Identifier for the speech utterance |
Complete Usage Example
ViewModel Integration
Lifecycle Management
Follow these best practices for managing the TTS controller lifecycle:
- Create the controller early (e.g., in
onCreate()) to allow initialization time - Use
speak()andstop()as needed during the component’s lifecycle - Destroy in
onDestroy()oronCleared()to release resources
Error Handling
The controller handles initialization failures gracefully:
- If TTS initialization fails, the
readyflag remainsfalse - All
speak()calls will return silently when not ready - No exceptions are thrown to the caller
Language Support
The controller is configured for Spanish (Chile):Queue Behavior
- New speech interrupts and replaces any ongoing speech
- Previous speech in the queue is discarded
TextToSpeech.QUEUE_ADD instead.
See Also
- SpeechController - Speech recognition controller
- Android TextToSpeech - Official documentation
- PhraseService - Service for managing phrases to speak