我有一个句子列表,我的目标是逐一阅读。 我正在使用目前仅在Chrome中支持的SpeechSynthesisUtterance功能。
以下代码有效:
list = ['This is sentence 1', 'This is sentence 2', 'This is sentence 3', 'This is sentence 4', 'This is sentence 5', 'This is sentence 6', 'This is sentence 7', 'This is sentence 8', 'This is sentence 9'];
if ('speechSynthesis' in window) {
for(i=0; i<9;i++) {
var msg = new SpeechSynthesisUtterance(list[i]);
window.speechSynthesis.speak(msg);
}
}
但我想在显示时显示文字。列表中的下一个项目应仅在前一个文本读取完成时显示。 示例代码位于http://jsfiddle.net/6d75q/
如果我现在运行它,所有列表项都会一起显示。有时浏览器会崩溃。
我尝试使用jquery延迟等待上一句显示下一句但是没有用。
我的问题是: 1)如何在读出文本时逐一显示项目? 2)为什么浏览器有时会崩溃
答案 0 :(得分:3)
以下是使用 onend 方法的代码的修改版本:
var list = ['This is sentence 1', 'This is sentence 2', 'This is sentence 3', 'This is sentence 4', 'This is sentence 5', 'This is sentence 6', 'This is sentence 7', 'This is sentence 8', 'This is sentence 9'];
if ('speechSynthesis' in window) PlaySpeech(0);
function PlaySpeech(i){
var speech = new SpeechSynthesisUtterance(list[i]);
speech.onend = function(){ setTimeout('PlaySpeech('+ (i+1)+')',250); };
console.log(list[i],speech);
window.speechSynthesis.speak(speech);
}