KOTLIN - textToSpeech 重复
KOTLIN - textToSpeech repeat
我想知道是否有可能一旦我打开文字转语音,文字转语音会不断读取值
currentItem.percent
这个值会不断更新,所以我希望每个新值都能被大声朗读
tts = TextToSpeech(Context, TextToSpeech.OnInitListener { status ->
if (status != TextToSpeech.ERROR) // if no error set language
tts.language = Locale.UK
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
);
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
);
上面的代码只是读取相同的百分比值两次?关于如何解决这个问题有什么想法吗?
编辑
我也试过这个循环但没有成功,应用程序没有读入新值并且每次都继续说相同的值
for (i in 0..6) {
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
);
您重复听到相同值的原因是 speak
方法不会等到语音合成完成后再返回。来自文档:
This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns.
这意味着当您多次重复调用 speak
时,您实际上只是多次将相同的值添加到队列中。
相反,您需要做的是在每次调用 speak
时引入一个短暂的延迟。一种方法是在 activity.
中使用 Handler
private val handler = Handler()
然后制作一个既能读取当前值又能排队新任务以便稍后再次读取的方法:
val delayMs = 2000
fun speakCurrentValue() {
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
)
handler.postDelayed(Runnable { speakCurrentValue() }, delayMs)
}
现在,在您调用 speakCurrentValue
后,它会继续排队等待稍后再次成为 运行。
我想知道是否有可能一旦我打开文字转语音,文字转语音会不断读取值
currentItem.percent
这个值会不断更新,所以我希望每个新值都能被大声朗读
tts = TextToSpeech(Context, TextToSpeech.OnInitListener { status ->
if (status != TextToSpeech.ERROR) // if no error set language
tts.language = Locale.UK
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
);
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
);
上面的代码只是读取相同的百分比值两次?关于如何解决这个问题有什么想法吗?
编辑
我也试过这个循环但没有成功,应用程序没有读入新值并且每次都继续说相同的值
for (i in 0..6) {
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
);
您重复听到相同值的原因是 speak
方法不会等到语音合成完成后再返回。来自文档:
This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns. The synthesis might not have finished (or even started!) at the time when this method returns.
这意味着当您多次重复调用 speak
时,您实际上只是多次将相同的值添加到队列中。
相反,您需要做的是在每次调用 speak
时引入一个短暂的延迟。一种方法是在 activity.
Handler
private val handler = Handler()
然后制作一个既能读取当前值又能排队新任务以便稍后再次读取的方法:
val delayMs = 2000
fun speakCurrentValue() {
tts.speak(
currentItem.percent.toString(),
TextToSpeech.QUEUE_ADD,
null,
""
)
handler.postDelayed(Runnable { speakCurrentValue() }, delayMs)
}
现在,在您调用 speakCurrentValue
后,它会继续排队等待稍后再次成为 运行。