Turn text into voice with Speechsynthesis

Asked

Viewed 63 times

1

I’m trying to play an audio text!

It was to display a list of voices and languages (Voice: Maria - Portuguese "en-BR", Voice: Anna - English "en-US", ...) select the desired one, write a text and play it in audio. However I am having problems and unsuccessfully to solve!

<body>

    Selecionar Voz: <select id="voiceList"></select><br><br>
    <input id="txtInput" /><br><br>
    <button id="btnSpeak">Falar!</button>

    <script>
        // Selecionando as id do HTML
        var txtInput = document.querySelector('#txtInput')
        var voiceList = document.querySelector('#voiceList')
        var btnSpeak = document.querySelector('#btnSpeak')

        // sintetizador
        var synth = window.SpeechSynthesis;
        var voices = []

        NewVoices()
        if (speechSynthesis !== undefined) {
            speechSynthesis.onvoiceschanged = NewVoices     
        }

        btnSpeak.addEventListener('click', () => {
            var toSpeak = new SpeechSynthesisUtterance(txtInput.value)
            var selectedVoiceName = voiceList.selectedOptions[0].getnAttribute('data-name')
            voices.forEach((voice) => {
                if (voice.name === selectedVoiceName) {
                    toSpeak.voice = voice
                }
            })

            synth.speak(toSpeak);
        })

        function NewVoices() {
            voices = synth.getVoices()
            var selectedIndex = voiceList.selectedIndex < 0 ? 0 : voiceList.selectedIndex
            voiceList.inneHTML= ''
            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
        }
    </script>

</body>
  • I already took a look at this example: https://github.com/rbmelolima/SpeechSynthesis ?

  • what problems are you having? submit a [mcve]

  • Most likely on this line: voiceList.selectedOptions[0].getnAttribute('data-name') in getnAttribute('data-name') which is incorrect, would be getAttribute('data-name')

1 answer

1

Occurs due to function getnAttribute is wrong! the correct would be getAttribute

Although I don’t necessarily need an answer (for future purposes, the tip!) and even for lack of some important details in your question, I suggest edit and add the criteria of How to create a Minimum, Complete and Verifiable example. It’s worth a lot to take a look!


First of all, look Speechsynthesis - Web Apis their estates and their supports, because it is an Experimental Technology, it becomes exciting! (particularly speaking..)

I made a small code "fix" without the function getAttribute As I mentioned above, your question does not meet the right criteria. Not knowing where this function fits, I decided to create the example without it, below:

const synth = window.speechSynthesis; // chamada SpeechSynthesis API
const input = document.querySelector('input'); // caixa de texto
const selectVoices = document.querySelector('select'); // lista de vozes

let voices = [];
function getVoices() { 
  voices = synth.getVoices(); // armazena as vozes no array
  voices.forEach((voice, index) => {
    selectVoices.add(new Option(`${voice.name} (${voice.lang})`, index)); // adiciona as informações na lista de seleção..
  });
}

window.addEventListener('load', () => { // ao ser concluído..
  getVoices(); // carrega as vozes..
  if (synth.onvoiceschanged !== undefined)
    synth.onvoiceschanged = getVoices; // checa e atualiza o evento
});

// dispara um evento ao clicar no botão!
document.querySelector('button').addEventListener('click', () => {
  var utter = new SpeechSynthesisUtterance(input.value); // responsável pelo que vai falar!
  utter.voice = voices[selectVoices.value]; // define qual será a voz..
  synth.speak(utter); // reproduz o audio!
});
<input type="text" placeholder="Insira o texto aqui.." />
<select></select>
<button>Fale!</button>

  • Works well, can even play with the Siri: Oi Siiri, você está aí?, but I can’t select the voice.

  • @Augustovasques can’t select the voice? is where? mobile or desktop?

  • I am on the windows 10 desktop using Chrome. Print: https://imgur.com/a/F3Svqx3

  • I don’t seem to have support yet in Chrome, I’m in Edge 92 (I believe I am a native browser class or implemented by Microsoft)

  • In Edge it is, converts the text to voice but it is not possible to select a voice.

  • @Augustovasques entrho! I will check here then return here.. change the answer code!

  • 1

    Take a look at this page https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/getVoices I have 50 voices installed in my system. That page lists them all. Link to the example listing available voices on https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/getVoices#example

  • 1

    @Augustovasques tries now! so far, the problem was just updating the event onvoiceschanged (the opposite of Edge who already does it automatically)

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.