2

我有一个句子列表,我的目标是一一读出来。我正在使用目前仅在 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 deferred 来等待上一句显示下一句,但这不起作用。

我的问题是:1)如何在朗读文本时一一显示项目?2)为什么浏览器有时会崩溃

4

1 回答 1

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);
    }
  1. 您可以更改日志以将其显示到页面上,因为它正在遍历数组。
  2. 浏览器因调用 speak 方法的循环结构而崩溃。
于 2016-03-11T15:51:00.323 回答