WebSocket使用Watson Speech-to-Text JS SDK立即关闭

时间:2018-07-19 18:53:02

标签: speech-to-text ibm-watson

使用https://github.com/watson-developer-cloud/speech-javascript-sdk中最新的watson-speech.js,尝试从提供的演示中使用此代码:

document.querySelector('#button').onclick = function () {

  fetch('myserverurl/api/token')
  .then(function(response) {
      return response.text();
  }).then(function (token) {

    var stream = WatsonSpeech.SpeechToText.recognizeMicrophone({
        token: token,
        outputElement: '#output' // CSS selector or DOM Element
    });

    stream.on('error', function(err) {
        console.log(err);
    });

    document.querySelector('#stop').onclick = function() {
      stream.stop();
    };

  }).catch(function(error) {
      console.log(error);
  });
};

尝试在Chrome控制台中启动连接后立即得到此错误: WebSocket已经处于CLOSING或CLOSED状态。

使用Chrome并在本地进行测试。

1 个答案:

答案 0 :(得分:0)

我认为这是一个范围界定错误。您是在var stream内声明then,这意味着then完整的stream一旦不再存在,将被自动清理。

在更高的作用域级别添加var stream = nulllet stream = null。您仍然可以在then块中将其初始化为

}).then(function (token) {
  stream = WatsonSpeech.SpeechToText.recognizeMicrophone({
          token: token,
          outputElement: '#output' // CSS selector or DOM Element
  });
  ...