Estoy tratando de dividir un área de texto por líneas y usar texto a voz para que luego se hable cada línea. En última instancia, me gustaría agregar un retraso de 5 segundos entre cada línea.
Pero el ciclo for no funciona como se esperaba, obtengo el valor de la primera línea, luego el valor de la última línea se repite para la longitud de la matriz.
P.ej. Entrada: A B C D
Salida: A, D, D, D
Esperado: A, B, C, D
document.querySelector("#start").addEventListener("click", () => { // Set the text property with the value of the textarea textInput = document.getElementById("textarea"); textArray = textInput.value.split(/\n/g); for (var i = 0; i<textArray.length; i++) { textInput = document.getElementById("textarea"); textArray = textInput.value.split(/\n/g); speech.text = textArray[i]; window.speechSynthesis.speak(speech); } });En caso de que el objeto de speech del OP sea una instancia de SpeechSynthesisUtterance , existe la posibilidad de escuchar los eventos de dicho objeto como start y end .
Por lo tanto, uno ya ha resuelto el problema de alimentar las líneas de texto de la matriz inmediatamente a través de un bucle for a speech.text que en su mayoría resultará en que se lean/hablen solo la primera y repetidamente los valores de la última línea.
Con la introducción de un controlador de eventos, también se puede retrasar el manejo de eventos a través de setTimeout como lo pretende el OP.
Y para crear un ciclo/bucle de líneas habladas retrasadas, uno podría pensar en utilizar un generador creado por una función de generador que produce las líneas aún disponibles/todavía por hablar.
function* createLinePool(value) { const listOfLines = String(value) .split(/\n/g) .map(line => line.trim()) .filter(line => line !== ''); let line; while (line = listOfLines.shift()) { yield line; } } function readTextAreaLineWise() { const recitation = new SpeechSynthesisUtterance(); const textInput = document.querySelector('#textarea'); const linePool = createLinePool(textInput.value); function readLine() { const nextLineItem = linePool.next(); if (!nextLineItem.done) { console.log({ nextLineItem }); recitation.text = nextLineItem.value; window.speechSynthesis.speak(recitation); } } recitation.addEventListener('end', () => { setTimeout(readLine, 2000); }); // trigger first line getting read. readLine(); } document .querySelector('#start') .addEventListener('click', readTextAreaLineWise); * { margin: 0; } .as-console-wrapper { min-height: 100%!important; width: 50%; left: auto!important; right: 0; } #textarea { width: 48%; } #start { display: block } <textarea id="textarea" cols="26" rows="9"> Hallo world. The quick brown fox, jumps over the lazy dog. </textarea> <button id="start">Start</button>