【发布时间】:2016-06-07 14:59:42
【问题描述】:
我尝试使用 ws 包通过 websocket 使用基本的 Speech-To-Text 服务。但是在成功打开连接并发送初始消息后,我再也没有得到listening 状态。
我也尝试发送音频和空二进制文件(表示上传过程已完成),但服务器总是返回close,代码为1000。
以下是我的代码
'use strict';
var fs = require('fs');
var request = require('request');
var WS = require('ws');
var wsURI = 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize?watson-token=[TOKEN]&model=en-UK_NarrowbandModell&x-watson-learning-opt-out=1';
var getTokenForm = {
method: 'GET',
uri: 'https://[USER_ID]:[PASSWORD]@stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api',
};
var filepath = 'C:/Temp/test1.wav';
request(getTokenForm, function(error, response, body) {
wsURI = wsURI.replace('[TOKEN]', body);
var message = {
'action': 'start',
'content-type': 'audio/wav',
'continuous': true,
'inactivity_timeout': -1
};
var ws = new WS(wsURI);
['message', 'error', 'close', 'open', 'connection'].forEach(function(eventName) {
ws.on(eventName, console.log.bind(console, eventName + ' event: '));
});
ws.on('open', function(evt) {
ws.send(JSON.stringify(message));
setTimeout(function timeout() {
var readStream = fs.createReadStream(filepath);
readStream.on('data', function(data) {
ws.send(data, {
binary: true,
mask: false,
});
});
readStream.on('end', function() {
ws.send(new Buffer(0), {
binary: true,
mask: false,
});
});
}, 1000);
});
ws.on('close', function(data) {
console.log(data)
});
});
也尝试直接发送文件(不带流)。
var sound = fs.readFileSync(filepath);
ws.send(sound, { binary: true, mask: false});
并尝试添加自定义标题Authorization
var authorization = 'Basic ' + new Buffer('USER_ID:PASSWORD').toString('base64');
var ws = new WS(wsURI, {
headers: {
'Authorization': authorization,
}
});
但到目前为止还没有运气。
【问题讨论】:
-
我可以使用code example from node sdk 成功获得结果,但我希望看到它在没有官方SDK 的情况下也能正常工作。
-
SDK 是有原因的
-
如果您想在浏览器中使用语音转文本,还有另一个 sdk。 github.com/watson-developer-cloud/speech-javascript-sdk
标签: node.js websocket speech-to-text ibm-watson