Introducción a la síntesis de voz con JavaScript. Creación de un formulario para probar la funcionalidad y los distintos tipos de voces.
¿Te has preguntado alguna vez cómo convertir texto en voz usando JavaScript? Gracias a la Web Speech API, podemos lograrlo de manera sencilla. Esta API proporciona, de forma nativa, herramientas para la síntesis de voz y el reconocimiento de voz directamente en el navegador, sin necesidad de librerías externas.
En este artículo, aprenderás cómo construir una aplicación básica que convierte texto escrito en voz utilizando HTML y JavaScript.
Primero, necesitamos crear una estructura básica en HTML. Incluiremos un área de texto para que el usuario pueda escribir lo que quiera convertir a voz y un botón para iniciar la lectura.
<!DOCTYPE html><html lang="es"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Texto a Voz con JavaScript</title></head><body> <h1>Convierte Texto a Voz</h1> <textarea id="texto" rows="10" cols="50" placeholder="Escribe algo aquí..."></textarea><br> <button id="leer">Leer Texto</button>
<script> // Aquí irá el código JavaScript </script></body></html>
En este código, tenemos:
<textarea>
donde el usuario escribirá el texto que desea escuchar.<button>
que, al hacer clic, activará la conversión de texto a voz.Ahora, vamos a añadir la funcionalidad en JavaScript.
La Web Speech API tiene un módulo llamado SpeechSynthesis
que nos permite convertir texto a voz. Aquí está el código necesario para hacer que nuestro botón lea el texto ingresado.
// Seleccionamos los elementos del DOMconst botonLeer = document.getElementById('leer');const areaTexto = document.getElementById('texto');
// Evento que se dispara al hacer clic en el botónbotonLeer.addEventListener('click', () => { const texto = areaTexto.value; // Obtenemos el texto del textarea if (texto.trim() !== '') { const utterance = new SpeechSynthesisUtterance(texto); // Creamos una instancia de SpeechSynthesisUtterance utterance.lang = 'es-ES'; // Configuramos el idioma (español de España) speechSynthesis.speak(utterance); // Iniciamos la lectura del texto } else { alert('Por favor, escribe algún texto para convertirlo en voz.'); }});
<textarea>
.SpeechSynthesisUtterance
: Esta clase convierte el texto en una instrucción que el navegador puede leer.utterance.lang = 'es-ES'
para asegurarnos de que la voz sea en español.speechSynthesis.speak(utterance)
para que el navegador pronuncie el texto.Pruébalo el formulario:
<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Texto a Voz con JavaScript</title> <style> </style></head>
<body> <h1>Convierte Texto a Voz</h1> <textarea id="texto" rows="10" cols="50" placeholder="Escribe algo aquí..."></textarea><br> <button id="leer">Leer Texto</button>
<script> // Seleccionamos los elementos del DOM const botonLeer = document.getElementById('leer'); const areaTexto = document.getElementById('texto');
// Evento que se dispara al hacer clic en el botón botonLeer.addEventListener('click', () => { const texto = areaTexto.value; // Obtenemos el texto del textarea if (texto.trim() !== '') { const utterance = new SpeechSynthesisUtterance(texto); // Creamos una instancia de SpeechSynthesisUtterance utterance.lang = 'es-ES'; // Configuramos el idioma (español de España) speechSynthesis.speak(utterance); // Iniciamos la lectura del texto } else { alert('Por favor, escribe algún texto para convertirlo en voz.'); } }); </script></body>
</html>
Podemos mejorar el ejemplo añadiendo más opciones, como seleccionar la voz.
Algunos navegadores ofrecen múltiples voces para diferentes idiomas. Podemos listar y permitir al usuario elegir la que prefiera:
const selectorVoz = document.createElement('select');document.body.insertBefore(selectorVoz, areaTexto);
let voces = [];
function cargarVoces() { voces = speechSynthesis.getVoices(); selectorVoz.innerHTML = '';
voces.forEach((voz, index) => { if (voz.lang.startsWith('es')) { // Filtramos solo voces en español const option = document.createElement('option'); option.value = index; option.textContent = `${voz.name} (${voz.lang})`; selectorVoz.appendChild(option); } });}
// Cargar voces (algunos navegadores requieren que sea dentro de un evento)speechSynthesis.onvoiceschanged = cargarVoces;
botonLeer.addEventListener('click', () => { const texto = areaTexto.value; if (texto.trim() !== '') { const utterance = new SpeechSynthesisUtterance(texto); const vozSeleccionada = voces[selectorVoz.value]; utterance.voice = vozSeleccionada; utterance.lang = vozSeleccionada.lang; speechSynthesis.speak(utterance); } else { alert('Por favor, escribe algún texto para convertirlo en voz.'); }});
Prueba esta versión actualizada con selección de voz:
<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Texto a Voz con JavaScript</title> <style> select { display: flex; margin-bottom: 8px; } </style></head>
<body> <h1>Convierte Texto a Voz</h1> <textarea id="texto" rows="10" cols="50" placeholder="Escribe algo aquí..."></textarea><br> <button id="leer">Leer Texto</button>
<script> // Seleccionamos los elementos del DOM const botonLeer = document.getElementById('leer'); const areaTexto = document.getElementById('texto'); const selectorVoz = document.createElement('select'); document.body.insertBefore(selectorVoz, areaTexto);
let voces = [];
function cargarVoces() { voces = speechSynthesis.getVoices(); selectorVoz.innerHTML = '';
voces.forEach((voz, index) => { if (voz.lang.startsWith('es')) { // Filtramos solo voces en español const option = document.createElement('option'); option.value = index; option.textContent = `${voz.name} (${voz.lang})`; selectorVoz.appendChild(option); } }); }
// Cargar voces (algunos navegadores requieren que sea dentro de un evento) speechSynthesis.onvoiceschanged = cargarVoces;
botonLeer.addEventListener('click', () => { const texto = areaTexto.value; if (texto.trim() !== '') { const utterance = new SpeechSynthesisUtterance(texto); const vozSeleccionada = voces[selectorVoz.value]; utterance.voice = vozSeleccionada; utterance.lang = vozSeleccionada.lang; speechSynthesis.speak(utterance); } else { alert('Por favor, escribe algún texto para convertirlo en voz.'); } }); </script></body>
</html>
¡Felicidades! Has construido una aplicación simple que convierte texto en voz utilizando HTML y JavaScript. Con la Web Speech API, no solo puedes leer texto en voz alta, sino también explorar otras funcionalidades como el reconocimiento de voz.
Este es solo el comienzo. ¿Qué tal si integras esta funcionalidad en una aplicación más grande o la combinas con comandos por voz para crear una experiencia más interactiva?