문제

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";
  }
}

도움이 되었습니까?

해결책

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top