2

Tengo un archivo templates/index.html. Cuando hace une clic sobre el primero botton, btn_query, deberia llamar a startDictation(), una funcion javascript para reconocimiento de voz. Pero hay un problema, que solo aparece sobre stackoverflow y con Chrome, con recognition.onresult = function (e){...}.

  1. No obtenemos el pop-up window.alert(5 + 6); al comienzo de la función
  2. la consola Stavkoverflow reconoce que hay un error y escribe: Recognition had an error. Pero no sé cuál.

    <!DOCTYPE html>
    <html style="margin: auto; display:table;">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
        </script>
        <script>var synth = window.speechSynthesis;</script>
        <!-- HTML5 Speech Recognition API -->
        <script>
                function startDictation() {
                    document.getElementById('transcript').value = '';
                    document.getElementById('output').value = '';
                    if (window.hasOwnProperty('webkitSpeechRecognition')) {
                        var recognition = new webkitSpeechRecognition();
                        recognition.continuous = false;
                        recognition.interimResults = false;
                        recognition.lang = "en-US";
                        recognition.start();
                        recognition.onresult = function (e) {
                            window.alert(5 + 6);
                            document.getElementById('loader').hidden = false;
                            document.getElementById('transcript').value = e.results[0][0].transcript;
                            recognition.stop();
                            var data = e.results[0][0].transcript;
                            $.post("http://localhost:5000/news_urls", { "data": data },
                            function (response) {
                            document.getElementById('loader').hidden = true;
                                data = response;
                                document.getElementById("output").value = data["urls"];
                            }).error(function (response) {
                            document.getElementById('loader').hidden = true;
                                if (response.status == 400)
                                    text = jQuery.parseJSON(response.responseText)["original_exception"];
                                else
                                    text = "I'm sorry. I did not get that.";
                                document.getElementById("output").value = text;
                            });
                        };
                        recognition.onerror = function (e) {
                            recognition.stop();
                            console.log("Recognition had an error");
                        }
                    }
                }
    
                function btnClick() {
    	                synth.cancel();
                        var utterThis = new SpeechSynthesisUtterance(document.getElementById("output").value);
                        utterThis.voice = synth.getVoices()[0];
                        utterThis.pitch = 1.0;
                        utterThis.rate = 0.8;
                        utterThis.onerror = function(e) { console.log("Something went wrong with utterance."); };
                        synth.speak(utterThis);
                }
        </script>
        <style>
            .speech {
                border: 0px solid #DDD;
                width: 600px;
                padding: 0;
                margin: 0;
                font-family: "Calibri";
            }
    
                .speech input {
                    border: 1;
                    width: 240px;
                    display: inline-block;
                    height: 30px;
                }
    
                .speech img {
                    float: right;
                    width: 40px;
                }
        </style>
    </head>
    
    <body bgcolor="#e2e2e2">
        <h1 style="font-family: Calibri;">Delbot</h1>
        <div class="speech" ><i>It understands your voice commands, searches news and knowledge sources, and summarizes and reads out content to you.</i></div>
        <br /><i class="speech"><font color="gray">Only tested on Windows PCs. Not tested on other PCs or mobile devices.</font></i>
    
        <div class="speech">
                <textarea style="width: 600px;font-family: Calibri;font-size:x-large" name="q" id="transcript"
                          placeholder="Your query will appear here after you speak." rows="2" readonly="True"></textarea>
                <br>
                <input id="btn_query" type="button" onclick="startDictation()" value="Query"
                       style="font-family: Calibri;" />
                <img src="static/loader.gif" width="100px" align="left" style="float: left" hidden="True" id="loader" />
                <br><br>
                <h2 class="speech">Results</h2>
                <textarea style="width: 600px;font-family: Calibri;font-size:x-large" id="output" rows="2" placeholder="Results will appear here."
                          readonly="True"></textarea>
                <input id="btn_speak" type="button" value="Speak" onclick="btnClick()" style="font-family: Calibri;" />
    
        </div>
    </body>
    </html>

9
  • Puedes poner el Script en el head ? el 24 jul. 2018 a las 15:50
  • ¿Marine1 qué navegador web estas usando?
    – FJSevilla
    el 24 jul. 2018 a las 15:52
  • @FJSevilla Firefox ! el 24 jul. 2018 a las 15:52
  • @LucianoMontañez ! Si por seguro, pero no cambia el resultado el 24 jul. 2018 a las 15:55
  • Robe el código y de hecho, si me ejecuta el window.alert(5 + 6); el 24 jul. 2018 a las 16:01

1 respuesta 1

2

Antes de nada, por favor usa HTTPS para referenciar a JQuery (https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js)

El método startDictation es invocado en cualquier navegador, esto incluye Firefox. Tu problema es el siguiente:

if (window.hasOwnProperty('webkitSpeechRecognition')) {
    ...
}

Solamente se entrará en este if si window tiene definido webkitSpeechRecognition. Esto nos lleva a la Web Speech API.

La API en cuestión está clasificada como experimental. Si un usuario quiere usarla en Firefox debe modificar la configuración del navegador como puedes ver en la web oficial:

https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API

Además, estás llamando a la API con prefijo (webKit) cuando deberías comprobar primero si existe la propiedad sin prefijo (SpeechRecognition) y hacer uso de ella si es así.

Espero que te sirva de ayuda.

Un saludo.

3
  • Quizas a lo mejor algo así: window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; y luego: if (window.SpeechRecognition) {...} el 20 mar. 2019 a las 20:57
  • @DamianGarcia por supuesto, pero la API sigue siendo experimental y en firefox el cliente debe habilitar un flag. Esta funcionalidad será increíble cuando sea estándar :) el 21 mar. 2019 a las 12:20
  • Es verdad, yo estoy haciendo algo también para mi sitio y sólo me funciona en Chrome. En firefox, Edge, IE...nada de nada y en Opera me sale un mensaje "Failed to execute 'start' on 'SpeechRecognition': recognition has already started." No sé que pasa con Safari. el 21 mar. 2019 a las 12:58

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.