Chrome中使用javascript语音转换文字并不能识别任何内容

时间:2014-04-08 09:15:17

标签: javascript html google-chrome speech-recognition

我正在尝试在JAVASCRIPT中编写一个代码,该代码使用语音输入并将其转换为文本并将此文本放入textarea(HTML)。我的代码如下所示。按钮看起来有点奇怪(比平时小),当你点击它时,它根本无法正常工作。请帮忙。

我的代码如下:

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

1 个答案:

答案 0 :(得分:6)

您似乎正在使用W3网站上的一些过时的示例代码:http://lists.w3.org/Archives/Public/public-speech-api/2012Oct/0032.html

您使用的是谷歌浏览器吗?打开JavaScript控制台,它应该揭示这个问题:

  

未捕获的ReferenceError:未定义SpeechRecognition

以下是 的示例页面:https://www.google.com/intl/en/chrome/demos/speech.html

全部是HTML5,因此您可以查看整个源代码并从中学习。玩得开心!

修改 使OP代码示例在Google Chrome上运行所需的最小更改:

  • SpeechRecognition替换为webkitSpeechRecognition
  • resultIndex替换为event.resultIndex
  • event.results.final替换为event.results[i].isFinal

结果代码:

<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>