I am triying to change the text to speech output langauge in android programmatically, because the arabic text to speech wont work unless the output text to speech langauge is arabic or atleast that is what i think maybe there is an other solution
i am basiclly tryna change the language here
i am wondering if i can do this programaticlly, i know that it exists a solution i just dont know it yet. or even if i cant can i redirect the user to that setting page so he can change it?
this is what i have tried:
class AndroidTextToSpeech(context: Context) : SeTextToSpeech {
// private val locale = Locale("ar")
private var ttsEngine: TextToSpeech = TextToSpeech(context) { status ->
if (status == TextToSpeech.SUCCESS) {
println("TextToSpeech initialized")
} else {
println("TextToSpeech failed to initialize")
}
}.apply {
// Locale.setDefault(locale)
language = Locale.forLanguageTag("ar")
// println("displayLanguage ${locale.displayLanguage}")
// println("Locale displayLanguage ${Locale.getDefault().displayLanguage}")
}
override fun convertTextToSpeech(message: String) {
KmpMainThread.runViaMainThread {
ttsEngine
.speak(message, TextToSpeech.QUEUE_FLUSH, null, null)
.also { println("speak $it") }
}
}
}
it seem that Locale dosent identify ar Languahe Tag but the request in the speak
function return 0 which mean it succeded but no audio have came out
I figured it out, turned out that the apply block wasn’t changing the language because of TextToSpeech.SUCCESS needed to be called before we could set the language, Now I instead added a delay that I would set the Language.
Final Code should look like this:
class AndroidTextToSpeech(context: Context) : SeTextToSpeech {
private val arLocale = Locale("ara")
private var ttsEngineHaveBeenInitialized = false
private var ttsEngine: TextToSpeech = TextToSpeech(context) { status ->
ttsEngineHaveBeenInitialized = status == TextToSpeech.SUCCESS
}
override fun convertTextToSpeech(message: String) {
if (ttsEngineHaveBeenInitialized){
if (ttsEngine.isLanguageAvailable(arLocale) == 0){
ttsEngine.setLanguage(arLocale)
}
}
ttsEngineHaveBeenInitialized = false
KmpMainThread.runViaMainThread {
ttsEngine.speak(message, TextToSpeech.QUEUE_FLUSH, null, null)
}
}
}