Ir al contenido


Foto

Trabajar con mas de dos Inputs con el Web Speech API de Google


  • Por favor identifícate para responder
1 respuesta en este tema

#1 luisf88

luisf88

    Newbie

  • Miembros
  • Pip
  • 1 mensajes

Escrito 09 junio 2014 - 10:48

Buenos días Ingenieros.

Acudo a ustedes con la siguiente duda.

Recientemente me ha sido asignado la creación de un formulario en el cual todos los inputs pueden ser llenados tanto manualmente, como por reconociemiento de voz, para lo cual se estaba usando el WebSpeechAPI de google, introduciendo unicamente el comando x-webkit-speech="x-webkit-speech" en todos los Inputs del formulario, sin embargo, google ha retirado el soporte para esta acción debido a una vulnerabilidad encontrada hace unos meses.

El API sigue funcionando pero usando el siguiente metodo:

Les pongo este codigo a modo de ejemplo:

Codigo HTML



delphi
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  6. <script type="text/javascript" src="voice.js"></script>
  7. </head>
  8. <body>
  9. <button id="start_button" onclick="startButton(event)"><img id="start_img" src="mic.gif" alt="Start"></button>
  10. <input type="text" id="cuadro" name="cuadro" placeholder="Prueba">
  11. </body>
  12. </html>



Codigo Javascript



delphi
  1. var recognizing = false;
  2.  
  3. if (!('webkitSpeechRecognition' in window))
  4. {
  5. upgrade();
  6. }
  7. else
  8. {
  9. //start_button.style.display = 'inline-block';
  10. var recognition = new webkitSpeechRecognition();
  11. recognition.continuous = false;//Me permite dejar encendido el microfono o apagarlo al terminar de hablar
  12. recognition.interimResults = false;//Me permite ver la edicion del texto o no
  13.  
  14. recognition.onstart = function()
  15. {
  16. recognizing = true;
  17. //showInfo('info_speak_now');
  18. start_img.src = 'mic-animate.gif';
  19. };
  20.  
  21. recognition.onerror = function(event)
  22. {
  23. if (event.error == 'no-speech')
  24. {
  25. start_img.src = 'mic.gif';
  26. //showInfo('info_no_speech');
  27. ignore_onend = true;
  28. }
  29. if (event.error == 'audio-capture')
  30. {
  31. start_img.src = 'mic.gif';
  32. //showInfo('info_no_microphone');
  33. ignore_onend = true;
  34. }
  35. if (event.error == 'not-allowed')
  36. {
  37. if (event.timeStamp - start_timestamp < 100)
  38. {
  39. //showInfo('info_blocked');
  40. }
  41. else
  42. {
  43. //showInfo('info_denied');
  44. }
  45. ignore_onend = true;
  46. }
  47. };
  48.  
  49. recognition.onend = function()
  50. {
  51. recognizing = false;
  52. if (ignore_onend)
  53. {
  54. return;
  55. }
  56. start_img.src = 'mic.gif';
  57. if (!final_transcript)
  58. {
  59. //showInfo('info_start');
  60. return;
  61. }
  62. //showInfo('');
  63. if (window.getSelection)
  64. {
  65. window.getSelection().removeAllRanges();
  66. var range = document.createRange();
  67. range.selectNode(document.getElementById('final_span'));
  68. window.getSelection().addRange(range);
  69. }
  70. if (create_email)
  71. {
  72. create_email = false;
  73. createEmail();
  74. }
  75. };
  76.  
  77. recognition.onresult = function(event)
  78. {
  79. var interim_transcript = '';
  80. for (var i = event.resultIndex; i < event.results.length; ++i)
  81. {
  82. if (event.results[i].isFinal)
  83. {
  84. final_transcript += event.results[i][0].transcript;
  85. }
  86. else
  87. {
  88. interim_transcript += event.results[i][0].transcript;
  89. }
  90. }
  91. //final_transcript = capitalize(final_transcript);
  92. //final_span.innerHTML = linebreak(final_transcript);
  93. //interim_span.innerHTML = linebreak(interim_transcript);
  94. if (final_transcript || interim_transcript)
  95. {
  96. //showButtons('inline-block');
  97. }
  98.  
  99. var Nombre=final_transcript;
  100. $("#cuadro").val(Nombre);
  101.  
  102. };
  103. }
  104.  
  105. //============================Desaparece los microfonos==============================
  106. function upgrade()
  107. {
  108. start_button.style.visibility = 'hidden';
  109. //showInfo('info_upgrade');
  110. }
  111. //===================================================================================
  112.  
  113. //============================Primera letra en mayuscula==============================
  114. var first_char = /\S/;
  115. function capitalize(s)
  116. {
  117. return s.replace(first_char, function(m) { return m.toUpperCase(); });
  118. }
  119. //===================================================================================
  120.  
  121. function startButton(event)
  122. {
  123. if (recognizing)
  124. {
  125. recognition.stop();
  126. return;
  127. }
  128. final_transcript = '';
  129. recognition.lang = 'es-CO'; //selecciona el idioma y dialecto;
  130. recognition.start();
  131. ignore_onend = false;
  132. //final_span.innerHTML = '';
  133. //interim_span.innerHTML = '';
  134. start_img.src = 'mic-slash.gif';
  135. //showInfo('info_allow');
  136. //showButtons('none');
  137. start_timestamp = event.timeStamp;
  138. }




Para el reconociemiento de voz, se necesita de un boton que llame a una funcion y luego esta pone el resultado en el Input, pero el formulario que se esta desarrollando tiene mas de 100 Inputs los cuales todos deben ser llenados con reconocimiento de voz, se que debo crear un boton para cada input, pero, ¿como puedo modificar el Javascript anterior para evitar tener 100 funciones diferentes para todos los inputs?

Espero que puedan ayudarme.

Muchas gracias de antemano.

Salu2
  • 0

#2 cadetill

cadetill

    Advanced Member

  • Moderadores
  • PipPipPip
  • 994 mensajes
  • LocationEspaña

Escrito 09 junio 2014 - 12:19

Buenas

En el OnClick del botón pásale un parámetro más que sea el nombre del Input. Con el nombre puedes buscarlo y asignarle el texto. Si no sabes cómo hacer la búsqueda, puedes leerte esta web
  • 0




IP.Board spam blocked by CleanTalk.