admin管理员组文章数量:1416661
I have created a class that initializes the TTS (Text-to-Speech) object and monitors when the initialization is complete. I also implemented two functions:
releaseOfTtsResources
toSpeak
package com.gtdvm.echopoint.utils
import android.content.Context
import android.provider.Settings
import android.speech.tts.TextToSpeech
import java.util.Locale
import android.util.Log
class TextToSpeechHelper(context: Context) : TextToSpeech.OnInitListener {
private var tts: TextToSpeech? = null
private var pendingText: String? = null
//private val ttsCreated: Boolean = false
init {
// initialize the synthesizer
Log.d(TTSTAG, "initialize the synthesizer")
//val tempTTS = TextToSpeech(context, null)
val userTTS = context.getSystemService(TextToSpeech::class.java)?.defaultEngine ?: "com.google.android.tts" //TextToSpeech.Engine.DEFAULT_ENGINE
//val userTTS = Settings.Secure.getString(context.contentResolver, Settings.Secure.TTS_DEFAULT_SYNTH) ?: "com.google.android.tts"
Log.d(TTSTAG, "Motor TTS select: $userTTS")
tts = TextToSpeech(context, this, userTTS)
}
override fun onInit(status: Int) {
//Set preferred language default is system language
Log.d(TTSTAG, "Set preferred language default is system language")
if (status == TextToSpeech.SUCCESS){
Log.d(TTSTAG, "TTS initialized successfully")
tts?.language = Locale.getDefault()
pendingText?.let { toSpeak(it) }
pendingText = null
} else{
Log.e(TTSTAG, "TTS initialization failed")
}
}
// Function to speak the text received as a parameter
fun toSpeak(text: String){
Log.d(TTSTAG, "the text is sent to the synthesizer")
if (tts?.language == null){
Log.d(TTSTAG, "TTS not initialized yet, storing text for later")
pendingText = text
} else{
tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, null)
}
}
// Release TTS resources (called in activity to avoid memory leaks)
fun releaseOfTtsResources(){
Log.d(TTSTAG, "Release TTS resources")
tts?.stop()
tts?.shutdown()
tts = null
}
companion object{
const val TTSTAG = "TextToSpeechHelper"
}
}
The issue I am facing is that my function always uses the system’s default synthesizer instead of the one selected by the user.
For example, if the user has installed Smart Voice on their phone and set it as the preferred TTS engine, my function still uses the system's default synthesizer (e.g., Google TTS or Samsung TTS).
How can I ensure that my function uses the user-selected TTS engine instead of the system's default? Any guidance or examples would be greatly appreciated.
NOTE:
- I am using the latest SDK, Android 15, and what I found is already deprecated because it was used in older Android versions. That’s why I need help, please.
本文标签:
版权声明:本文标题:android - Automatic detection of the TTS selected by the user and initialization of the TTS class constructor - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745256091a2650111.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论