1
resposta

Voz não está funcionando

Olá, pessoal. Tudo bem?

Fiz as alterações, mas a voz do leitor continua não funcionando. Vou deixar os códigos aqui para facilitar a investigação.

app.js

let listaDeNumerosSorteados = [];
let numeroLimite = 10;  
let numeroSecreto = gerarNumeroAleatorio(); 
let tentativas = 1; 


function exibirTextoNaTela(tag, texto){
    let campo = document.querySelector(tag, texto); 
    campo.innerHTML = texto;
    if ('speechSynthesis' in window) {
        let utterance = new SpeechSynthesisUtterance(texto);
        utterance.lang = 'pt-BR'; 
        utterance.rate = 1.2; 
        window.speechSynthesis.speak(utterance); 
    } else {
        console.log("Web Speech API não suportada neste navegador.");
    } 
}
function exibirMensagemInicial(){
    exibirTextoNaTela('h1', 'Jogo do número secreto'); 
    exibirTextoNaTela('p', 'Escolha um número entre 1 e 10');
}

exibirMensagemInicial(); 

function verificarChute() {
    let chute = document.querySelector('input').value; 

    if (chute == numeroSecreto){
        exibirTextoNaTela('h1', 'Acertou!');
        let palavraTentativa = tentativas > 1? 'tentativas' : 'tentativa'; 
        let mensagemTentativas = `Você descobriu o número secreto com ${tentativas} ${palavraTentativa}!`;
        exibirTextoNaTela('p', mensagemTentativas);
        document.getElementById('reiniciar').removeAttribute('disabled'); 
    } else {
        if (chute > numeroSecreto){
            exibirTextoNaTela('p', 'O número secreto é menor');
        } else {
            exibirTextoNaTela('p', 'O número secreto é maior'); 
        }
        tentativas++; 
        limparCampo(); 
    }
}

function gerarNumeroAleatorio() {
    let numeroEscolhido = parseInt(Math.random() * numeroLimite + 1); 
    let quantidadeDeElementosNaLista = listaDeNumerosSorteados.length; 

    if (quantidadeDeElementosNaLista == numeroLimite ){
        listaDeNumerosSorteados = []; 
    }
    if (listaDeNumerosSorteados.includes(numeroEscolhido)){
        return gerarNumeroAleatorio(); 
    } else {
        listaDeNumerosSorteados.push(numeroEscolhido); 
        console.log(listaDeNumerosSorteados); 
        return numeroEscolhido; 
    }
}

function limparCampo(){
    chute = document.querySelector('input'); 
    chute.value = ''; 
}

function reiniciarJogo(){
    numeroSecreto = gerarNumeroAleatorio(); 
    limparCampo(); 
    tentativas = 1; 
    exibirMensagemInicial();    
    document.getElementById('reiniciar').setAttribute('disabled', true); 
}

index.html

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@700&family=Inter:wght@400;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <title>JS Game</title>
</head>

<body>

    <div class="container">
        <div class="container__conteudo">
            <div class="container__informacoes">
                <div class="container__texto">
                    <h1></h1>
                    <p class="texto__paragrafo"></p>
                </div>
                <input type="number" min="1" max="10" class="container__input">
                <div class="chute container__botoes">
                    <button onclick="verificarChute()" class="container__botao">Chutar</button>
                    <button onclick="reiniciarJogo()" id="reiniciar" class="container__botao" disabled>Novo jogo</button>
                </div>
            </div>
            <img src="./img/ia.png" alt="Uma pessoa olhando para a esquerda" class="container__imagem-pessoa" />
        </div>
    </div>




    <script src="app.js" defer></script>
</body>

</html>

O projeto funciona normalmente, mas a voz não sai. Estou usando o Chrome como navegador.

1 resposta

Oi Natalia.guimaraes,

Analisando seu código, identifiquei que o problema está na forma como você está selecionando o elemento HTML dentro da função exibirTextoNaTela. O método querySelector espera apenas um seletor como argumento, e você está passando dois (tag, texto). Isso faz com que a função não encontre o elemento correto e a voz não seja reproduzida.

Para corrigir, você deve remover o segundo argumento do querySelector, deixando apenas o seletor da tag. O texto que será exibido deve ser atribuído ao innerHTML do elemento selecionado.

Aqui está a correção na função exibirTextoNaTela:

function exibirTextoNaTela(tag, texto){
    let campo = document.querySelector(tag); 
    campo.innerHTML = texto;
    if ('speechSynthesis' in window) {
        let utterance = new SpeechSynthesisUtterance(texto);
        utterance.lang = 'pt-BR'; 
        utterance.rate = 1.2; 
        window.speechSynthesis.speak(utterance); 
    } else {
        console.log("Web Speech API não suportada neste navegador.");
    } 
}

Com essa alteração, a voz deve funcionar corretamente ao exibir os textos na tela.

tux matrix    Caso este post o tenha ajudado, por favor, marcar como solucionado ☑️. Bons Estudos! 🤓