使用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并在本地进行测试。
答案 0 :(得分:0)
我认为这是一个范围界定错误。您是在var stream
内声明then
,这意味着then
完整的stream
一旦不再存在,将被自动清理。
在更高的作用域级别添加var stream = null
或let stream = null
。您仍然可以在then
块中将其初始化为
}).then(function (token) {
stream = WatsonSpeech.SpeechToText.recognizeMicrophone({
token: token,
outputElement: '#output' // CSS selector or DOM Element
});
...