Como principiante, estaba haciendo un proyecto de texto a voz.
Ahora funciona bien, pero quiero cambiar la input con p , div u otras etiquetas.
Eso significa que quiero reemplazar (etiqueta de input ) con otros. Ahora, ¿cómo puedo hacer eso?
Y también quiero eliminar la opción ( select etiqueta) como deseo. Ayúdame amablemente.
var txtInput = document.querySelector('#txtInput'); var voiceList = document.querySelector('#voiceList'); var btnSpeak = document.querySelector('#btnSpeak'); var synth = window.speechSynthesis; var voices = []; PopulateVoices(); if (speechSynthesis !== undefined) { speechSynthesis.onvoiceschanged = PopulateVoices; } btnSpeak.addEventListener('click', () => { var toSpeak = new SpeechSynthesisUtterance(txtInput.value); var selectedVoiceName = voiceList.selectedOptions[0].getAttribute('data-name'); voices.forEach((voice) => { if (voice.name === selectedVoiceName) { toSpeak.voice = voice; } }); synth.speak(toSpeak); }); function PopulateVoices() { voices = synth.getVoices(); var selectedIndex = voiceList.selectedIndex < 0 ? 0 : voiceList.selectedIndex; voiceList.innerHTML = ''; voices.forEach((voice) => { var listItem = document.createElement('option'); listItem.textContent = voice.name; listItem.setAttribute('data-lang', voice.lang); listItem.setAttribute('data-name', voice.name); voiceList.appendChild(listItem); }); voiceList.selectedIndex = selectedIndex; } <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> Select Voice: <select id='voiceList'></select> <br><br> <input id='txtInput' /> <br><br> <button id='btnSpeak'>Speak!</button> </body>OK, el código que he escrito es mucho más simple. Voy a intentar de explicar:
HTML:
<p id="txtInput">Speak this text</p> // change to paragraph element but keep the same ID <button id='btnSpeak'>Speak!</button>JavaScript:
var txtInput = document.querySelector('#txtInput'); var btnSpeak = document.querySelector('#btnSpeak'); var synth = window.speechSynthesis; var voices = []; PopulateVoices(); if(speechSynthesis !== undefined){ speechSynthesis.onvoiceschanged = PopulateVoices; } btnSpeak.addEventListener('click', ()=> { var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent); toSpeak.voice = voices[7]; // Spanish synth.speak(toSpeak); }); function PopulateVoices(){ voices = synth.getVoices(); voices.forEach((item, index) => console.log(item.name, index)); } Lo principal a tener en cuenta, cambié la entrada a un elemento de párrafo pero le asigné la misma ID (esto significa que el nombre de la ID y el elemento ya no tienen sentido txtInput para un párrafo, etc., pero eso es académico). Solo debe existir una ID en el DOM en cualquier momento, así que asegúrese de eliminar el otro elemento si es un duplicado o puede cambiar la ID del elemento y actualizar el selector js así
<p id="foo">Text</a> var elementID = document.querySelector('#foo');En la función anterior, obtiene el valor del texto de entrada usando:
var toSpeak = new SpeechSynthesisUtterance(txtInput.value);Debido a que el elemento de párrafo no tiene un atributo de valor, cambiamos esto a:
var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);Lo que devolverá el contenido del texto interno.
Obtengo la matriz de voces de la API y, con fines de depuración, estoy registrando en la consola todos los nombres e índices de voz:
voices.forEach((item, index) => console.log(item.name, index));Que devuelve por ejemplo:
Microsoft David - English (United States) 0 Microsoft Mark - English (United States) 1 Microsoft Zira - English (United States) 2 ...Esto me muestra cada voz en la consola, por ahora he configurado el índice 7 (que es Google español) como la voz preestablecida. Tendrás que actualizar el índice de la voz que quieras en:
toSpeak.voice = voices[7]; // SpanishEspero que esto tenga sentido, el código ahora está mezclando la sintaxis de estilo ES5 (y más antigua) con versiones más modernas, que no es mi preferencia, pero esto debería funcionar como se esperaba.
También hay un jsfiddle con el que puedes experimentar