我正在尝试在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";
}
}
答案 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>