Reputation: 337
I'm building an app that speaks a custom message that includes the current time. I've noticed that some voices seem to parse the time correctly- that is, when I pass in a string like "The time is now 7:07" it actually speaks it as "seven-oh-seven."
However, other voices insist on saying "the time is now seven colon zero seven." It would be simple enough to write a function to parse it myself, but I'm trying to find something built-in so I won't have to worry about localization. Is there something I can do within TTS (attributed-string-related, maybe?) or even a Java library that will provide me with a localized "text" string of a time? I've dug through the TTS documentation and didn't find anything, and all the Java time-formatting patterns I've seen are numbers-only, no words.
Upvotes: 0
Views: 476
Reputation: 337
Figured it out- the TtsSpan is what's needed. Took me a while to get the format right; there are basically zero examples out there on how to do this. Here are the basics for what worked for me, if anyone else comes across this with the same need (in kotlin):
var h:Int = Calendar.getInstance().get(Calendar.HOUR)
if (DateFormat.is24HourFormat(ApplicationContext))
h = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
val m:Int = Calendar.getInstance().get(Calendar.MINUTE)
val whenStr = getFormattedTime() // internal function I'm using to format it visually
wholeString = message.replace("|TIME|",whenStr) // my time doesn't always appear at the same place in the custom message
val spannedMsg:Spannable = SpannableString(wholeString)
val span:TtsSpan = TtsSpan.TimeBuilder(h, m).build()
spannedMsg.setSpan(span, wholeString.inexOf(whenStr),wholeString.indexOf(whenStr) + whenStr.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tts.speak(spannedMsg, TextToSpeech.QUEUE_FLUSH, params, "UTT_ID")
According to the TtsSpan documenation page, there are plenty of other options aside from TimeBuilder, as well, so be sure to check that out if you're looking for different customizations- just be aware that there aren't any code examples.
Upvotes: 3