Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
Text to speech with javascript?

As a beginner, I was making a text-to-speech project.

Now it's working fine, But I want to change the input with p, div, or others tags.

That means I want to replace (input tag) with others. Now how can I do that?

And also I want to remove the (select tag) option as my wish. Help me kindly.

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>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

OK, the code I have written is much simpler. I will try to explain:

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));
        }

Main things to note, I changed the input to a paragraph element but assigned it the same ID (this means that the name of the ID and element no longer really make sense txtInput for a paragraph etc, but that is academic). Only one ID should exist in the DOM at any one time, so make sure you remove the other element if it is a duplicate or you can change the ID of the element and update the js selector like so

<p id="foo">Text</a>

var elementID = document.querySelector('#foo');

In the previous function you are getting the value of the input text using:

var toSpeak = new SpeechSynthesisUtterance(txtInput.value);

Because the paragraph element does not have a value attribute we change this to:

var toSpeak = new SpeechSynthesisUtterance(txtInput.textContent);

Which will return the inner text content.

I get the array of voices from the API, and for debugging purposes I am console logging all the the voice names and indices:

voices.forEach((item, index) => console.log(item.name, index));

Which returns for example:

Microsoft David - English (United States) 0
Microsoft Mark - English (United States) 1
Microsoft Zira - English (United States) 2
...

This shows me each voice in the console, for now I have set index 7 (which is Google español) as the preset voice. You will have to update the index for the voice that you want in:

toSpeak.voice = voices[7]; // Spanish

I hope this makes sense, the code is now mixing ES5 style syntax (and older) with more modern versions, which is not my preference, but this should work as expected.

There is also a jsfiddle you can experiment with

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda