0

我正在使用以下演示来识别语音。它正在工作,但有时需要更多时间来加载或识别语音文本。不知道为什么会这样!但是有没有办法为识别函数设置默认超时,以便如果超过默认最大超时然后调用另一个回调函数?

<script>
  // Test browser support
  window.SpeechRecognition = window.SpeechRecognition       ||
                             window.webkitSpeechRecognition ||
                             null;

  if (window.SpeechRecognition === null) {
    document.getElementById('ws-unsupported').classList.remove('hidden');
    document.getElementById('button-play-ws').setAttribute('disabled', 'disabled');
    document.getElementById('button-stop-ws').setAttribute('disabled', 'disabled');
  } else {
    var recognizer = new window.SpeechRecognition();
    var transcription = document.getElementById('transcription');
    var log = document.getElementById('log');

    // Recogniser doesn't stop listening even if the user pauses
    recognizer.continuous = true;

    // Start recognising
    recognizer.onresult = function(event) {
      transcription.textContent = '';

      for (var i = event.resultIndex; i < event.results.length; i++) {
        if (event.results[i].isFinal) {
          transcription.textContent = event.results[i][0].transcript + ' (Confidence: ' + event.results[i][0].confidence + ')';
        } else {
          transcription.textContent += event.results[i][0].transcript;
        }
      }
    };

    // Listen for errors
    recognizer.onerror = function(event) {
      log.innerHTML = 'Recognition error: ' + event.message + '<br />' + log.innerHTML;
    };

    document.getElementById('button-play-ws').addEventListener('click', function() {
      // Set if we need interim results
      recognizer.interimResults = document.querySelector('input[name="recognition-type"][value="interim"]').checked;

      try {
        recognizer.start();
        log.innerHTML = 'Recognition started' + '<br />' + log.innerHTML;
      } catch(ex) {
        log.innerHTML = 'Recognition error: ' + ex.message + '<br />' + log.innerHTML;
      }
    });

    document.getElementById('button-stop-ws').addEventListener('click', function() {
      recognizer.stop();
      log.innerHTML = 'Recognition stopped' + '<br />' + log.innerHTML;
    });

    document.getElementById('clear-all').addEventListener('click', function() {
      transcription.textContent = '';
      log.textContent = '';
    });
  }
</script>

提前致谢!

4

1 回答 1

-1

不要忘记使用 onspeechend 功能。此功能检测语音何时结束,因此您可以在语音结束时输入您想要的指令。

您希望在您停止讲话时结束识别,因此:

例子:

recognition.onspeechend = function() {
  recognition.stop();
}
于 2016-02-16T16:16:14.987 回答