Reputation: 3139
I have a list of sentences and my objective is to read them out one by one. I am using SpeechSynthesisUtterance feature currently supported only in Chrome.
The following code works:
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);
}
}
But I want to display text as it reads out. The next items in the list should show up only when the previous text reading is finished. The example code is at http://jsfiddle.net/6d75q/
If I run this as of now all the list items are shown together. Sometimes the browser crashes.
I tried using jquery deferred to wait for previous sentence to show next one but that did not work.
My questions are: 1) How to show the items one by one as the text is read out? 2) Why is the browser crashing at times
Upvotes: 2
Views: 1964
Reputation: 85
Here is a modified version of your code that uses the onend method:
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);
}
Upvotes: 3