我正在尝试在javascript代码中使用Watson文本到语音服务。 但是,我一直在努力让它发挥作用。
如果我使用以下代码:
$.ajax({
url: 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize',
type: 'POST',
headers: {"Content-Type": "application/json", "Accept": "audio/*", "Authorization": "Basic SomethingSomethingSomething=="},
text: msgData.message[0].cInfo.text,
output: 'output.wav',
success: function() {
console.log("text to voice complete");
var audio = new Audio('output.wav');
audio.play();
}
});
我明白了:
无法加载 https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize: 请求标头字段不允许授权 预检响应中的Access-Control-Allow-Headers。
请注意,我可以很容易地从Restlet获得这样的请求。
但是,如果我使用:
$.ajax({
url: 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize',
type: 'POST',
user: {"something": "something"},
headers: {"Content-Type": "application/json", "Accept": "audio/*"},
data: {"text": msgData.message[0].cInfo.body},
output: 'output.wav',
success: function() {
console.log("text to voice complete");
var audio = new Audio('output.wav');
audio.play();
}
});
我明白了:
stream.watsonplatform.net/text-to-speech/api/v1/synthesize:1 POST https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize 401 (Processed)
index.html:1 Failed to load https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://52.207.232.200' is therefore not allowed access. The response had HTTP status code 401.
答案 0 :(得分:1)
看起来IBM Watson Text To Speech确实支持部分 CORS(在您的情况下需要)。请检查答案: Can't access IBM Watson API locally due to CORS on a Rails/AJAX App
此外,您还可以在那里找到明智的建议,告知您不在您的JavaScript代码中添加您的Watson凭据,而是使用令牌: https://console.bluemix.net/docs/services/watson/getting-started-tokens.html#tokens-for-authentication
当您在客户端工作时,也许尝试使用Watson的NPM模块或库(带示例)将是一个不错的选择:
https://www.npmjs.com/package/watson-speech
https://watson-speech.mybluemix.net/text-to-speech.html
希望这有帮助!