1

Estou tentando reproduzir um texto em áudio!

Era para exibir uma lista com as vozes e línguas (Voz: Maria - Português "pt-BR", Voz: Anna - Inglês "en-US", ...) selecionar a desejada, escrever um texto e assim reproduzi-la em áudio. Porém estou tendo problemas e sem sucesso para resolver!

<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>
3

1 Resposta 1

1

Ocorre devido a função getnAttribute está errada! o correto seria getAttribute

Apesar de necessariamente não precisar de uma resposta (para fins futuros, fica ai a dica!) e inclusive por falta de alguns detalhes importantes em sua pergunta, sugiro editar ela e adicionar os critérios de Como criar um exemplo Mínimo, Completo e Verificável. Vale muito apena dar uma olhada!


Antes de mais nada, veja SpeechSynthesis - APIs da Web suas propriedades e seus suportes, por se tratar de uma Tecnologia Experimental, torna-se empolgante! (particularmente falando..)

Fiz um pequeno código de "correção" sem a função getAttribute pois como mencionei acima, sua pergunta não está atendendo os devidos critérios. Por não saber onde se enquadra esta função, decidi criar o exemplo sem ela, abaixo:

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>

8

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .