[英]How to use the Watson Text2Speech REST API in a cordova App?
有很多示例:如何在Node.JS中使用Watson服務,但如果您使用帶有HTTP調用的REST API,我會遇到授權問題。
API的文檔講述了命令行curl接口,但沒有針對使用javascript的 Web或混合應用程序的HTTP調用的具體示例。
在我的情況下,我想在Cordova Mobile APP中使用Watson Text2Speech,為此我將建立一個工廠。
我使用的http調用適用於其他API, 但我在這里做錯了什么? 任何遺漏的格式?
有人可以幫忙嗎?
看起來像這樣:
.factory('GetSpeech', ['$http','$cordovaDialogs','$cordovaMedia','Base64', function($http,
$cordovaDialogs,
$cordovaMedia,
Base64){
// http://ngcordova.com/docs/plugins/media/
// https://www.ibm.com/watson/developercloud/doc/speech-to-text/input.shtml
// https://www.npmjs.com/package/cordova-plugin-speech-recognition-feat-siri
var watson_url = "https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize";
var watson_token_url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/text-to-speech/api";
var watson_token = "";
var username='YOUR_KEY';
var password='YOUR_PW';
var authdata = 'Basic ' + Base64.encode(username + ':' + password);
console.log(">>> Watson - authdata: ",authdata);
var the_get_header = "{'Authorization':'"+ authdata +"','Content-Type':'application/json'}";
var message = "";
var getSpeech_innner = function (){ $http({method: 'GET',
url: watson_token_url,
headers: the_get_header
}).then( function successCallback(response) {
console.log(">>> GetToken Success:",response);
watson_token=response;
var the_post_header = "{'X-Watson-Authorization-Token':'"+ watson_token +"','Content-Type':'application/json','Accept':'audio/wav'}";
var the_post_text = JSON.stringify({ "text":"This is the first sentence of the paragraph. Here is another sentence. Finally, this is the last sentence."
});
$http({
method: 'POST',
url: watson_url,
headers: the_post_header,
data: the_post_text
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log(">>> GetSpeech Success:",response);
message = "Success: " + response;
alert(message);
return true;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(">>> GetSpeech Error:",response);
message = "Error: " + response;
alert(message);
return false;
})
}, function errorCallback(response) {
console.log(">>> GetToken Error:",response);
});
};
return {
getSpeech : getSpeech_innner
};
}])
注意:順便說一下郵遞員的HTTP調用工作。 GET令牌和POST合成 。
我也嘗試過類似的方法:
$http({
method: 'POST',
url: tts_url,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'access-control-allow-headers, Authorization',
'content-type': 'application/json',
'Authorization': 'Basic <base64(uid:password)>',
'Accept': 'audio/wav'
},
data: {'\"text\"': '\"hello world\"' },
output: 'hello_world.wav'
}).then(function successCallback(response) {
console.log(">>> Success:",response.status);
}, function errorCallback(response) {
console.log(">>> Error:", response.status);
});
我會收到這個錯誤:
跨源請求已阻止:同源策略不允許在https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize上讀取遠程資源。 (原因:在CORS預檢頻道的CORS標題'Access-Control-Allow-Headers'中遺漏了令牌'access-control-allow-headers')。
當我刪除“Access-Control-Allow-Headers”標題中的“access-control-allow-headers”條目時,行為是相同的...
在郵遞員中運行相同的工作正常。
如何允許我的cordova應用程序呼叫遠程資源?
您是否stream.watsonplatform.net
您的Cordova應用程序中的stream.watsonplatform.net
源列入白名單? 在我看來,域名被阻止了。 有關列入白名單的詳細信息: https : //cordova.apache.org/docs/en/latest/guide/appdev/whitelist/
我的情況我想直接從服務經紀人那里獲得一個令牌。
在目前的情況下,似乎與text2speech服務的通信,我需要一個額外的服務器應用程序 ,例如在Node.JS服務器上運行,它為cordova應用程序客戶端提供令牌 。
文檔中提供了服務器令牌應用程序的示例代碼。
這在使用令牌的主題中的編程模型一章中有記錄。 Watson文檔鏈接
這與沃森服務的開發模型有關。 原因是允許Postman和CURL調用,Web或移動應用程序的其他請求不是有效的Origins。
因此,您無法直接從移動應用程序或Web應用程序使用REST API。 同樣的情況是使用Watson IoT。 這就是我使用Browserify 示例GitHub項目在Angular Web App中使用節點框架的原因:browserfied-ibmiotf-webapplication
為了更好地理解Watson API文檔中的一張圖片。 這在使用令牌的主題中的編程模型一章中有記錄。 Watson文檔鏈接
@謝謝雷內和安德魯指着我這個方向。
現在我有一個使用Text2Speech的有效的cordova應用程序。 我不在此示例中使用令牌 ,語音直接從Node.JS服務器提供給移動應用程序。
@謝謝 Andrii,提供一些代碼來做到這一點。
Node.JS服務器:
app.get('/getText2SpeechOutput', function (req, res) {
console.log(' -> text function called');
console.log(' calling watson to synthesize -> ', req.header('synthesize-text'));
var text_to_speech_l = new Text2speech({
username: req.header('service-username'),
password: req.header('service-password'),
});
var params = {
text: req.header('synthesize-text'),
voice: 'en-US_AllisonVoice',
accept: 'audio/wav'
};
var tempaudio = text_to_speech_l.synthesize(params);
console.log(' response received from Watson');
var reader = new wav.Reader();
reader.on('format', function (format) {
console.log(' file read success');
var writer = new wav.FileWriter('output.wav', {
channels: 1,
sampleRate: 22050,
bitDepth: 16
});
reader.pipe(writer);
console.log(' file write success');
writer.pipe(res)
console.log(' <- response provided');
});
tempaudio.pipe(reader);
})
Cordova App:
var getSpeech_innner = function (thetext, callback){
//const fileTransfer = new FileTransfer();
var headers = {
"Authorization": authdata,
"Accept": "audio/wav",
"synthesize-text": thetext,
"service-username": username,
"service-password": password
};
var options = {
headers: headers,
replace: true
};
$cordovaFileTransfer.download(get_speech_url , cordova.file.dataDirectory + 'speech.wav', options, true).then(
function (FileEntry) {
console.debug('>>> Success', FileEntry);
var filePath = cordova.file.dataDirectory + 'speech.wav';
callback(filePath);
},
function (error) {
console.debug('>>> download failure', error);
callback(error);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.