Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speech-to-text with javascript in Chrome doesn't recognize anything

I am trying to write a code in JAVASCRIPT which takes an input using voice and converts it into text and puts this text into textarea(HTML). My code is as shown below. The button appears kinda strange(smaller than usual) and when you click it, it doesnt work as desired. Please help.

My code is as follows:

<textarea id="textarea" rows=10 cols=80></textarea>
<button id="button" onclick="toggleStartStop()"></button>

<script type="text/javascript">
var recognizing;
var recognition = new SpeechRecognition();
recognition.continuous = true;
reset();
recognition.onend = reset();

recognition.onresult = function (event) {
  for (var i = resultIndex; i < event.results.length; ++i) {
    if (event.results.final) {
      textarea.value += event.results[i][0].transcript;
    }
  }
}

function reset() {
  recognizing = false;
  button.innerHTML = "Click to Speak";
}

function toggleStartStop() {
  if (recognizing) {
    recognition.stop();
    reset();
  } else {
    recognition.start();
    recognizing = true;
    button.innerHTML = "Click to Stop";
  }
}

like image 344
Akhilesh Bhatia Avatar asked Dec 20 '22 16:12

Akhilesh Bhatia


1 Answers

Looks like you are using some outdated sample code from the W3 site: http://lists.w3.org/Archives/Public/public-speech-api/2012Oct/0032.html

Are you using Google Chrome? Open the JavaScript console, it should reveal this problem:

Uncaught ReferenceError: SpeechRecognition is not defined

Here's a sample page that does work: https://www.google.com/intl/en/chrome/demos/speech.html

It's all HTML5, so you can have a look at the entire source and learn from it. Have fun!

EDIT: Minimum changes needed to make OP's code sample work on Google Chrome:

  • replace SpeechRecognition by webkitSpeechRecognition
  • replace resultIndex by event.resultIndex
  • replace event.results.final by event.results[i].isFinal

Resulting code:

<textarea id="textarea" rows=10 cols=80></textarea>
<button id="button" onclick="toggleStartStop()"></button>

<script type="text/javascript">
var recognizing;
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
reset();
recognition.onend = reset();

recognition.onresult = function (event) {
  for (var i = event.resultIndex; i < event.results.length; ++i) {
    if (event.results[i].isFinal) {
      textarea.value += event.results[i][0].transcript;
    }
  }
}

function reset() {
  recognizing = false;
  button.innerHTML = "Click to Speak";
}

function toggleStartStop() {
  if (recognizing) {
    recognition.stop();
    reset();
  } else {
    recognition.start();
    recognizing = true;
    button.innerHTML = "Click to Stop";
  }
}
</script>
like image 133
Ruud Helderman Avatar answered Dec 24 '22 03:12

Ruud Helderman