Thomas Suedbroecker Thomas Suedbroecker -4 years ago 183
Javascript Question

How to use the Watson Text2Speech REST API in a cordova App?

There are many samples: How to use Watson Services in Node.JS, but if you using the REST API with HTTP calls I run into problems with the authorization.

The documentation of the API tells about the commandline curl interface,
but there is no concrete sample for HTTP calls for web or Hybrid Applications using javascript.

In my situation I want to use the Watson Text2Speech in a cordova Mobile APP, for this I going to build a factory.

The http calls I use do work for other APIs, but what I am doing wrong here?
Any missing format?

Can anyone help?

Which looks like this:

.factory('GetSpeech', ['$http','$cordovaDialogs','$cordovaMedia','Base64', function($http,
var watson_url = "";
var watson_token_url = "";
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);
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."
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;
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;
return false;
}, function errorCallback(response) {
console.log(">>> GetToken Error:",response);
return {
getSpeech : getSpeech_innner


enter image description here

NOTE: By the way in the postman the HTTP calls working. The GET Token and the POST synthesize.

Answer Source

I my situation I wanted to get a token directly from the service broker.

At the current situation it seems for the communication with the text2speech service , I need a extra server app, for example running on Node.JS Server, which provides the token for the cordova app client.

Sample code for the server token app is available in the documentation.

This is documented in the chapter programming models in topic using token.

Here one picture from the documentation.

enter image description here

@Thanks to Rene and Andrew pointing me in this direction.

Now I have a working cordova app with Text2Speech. @Thanks to Andrii

Node.JS Server:

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


        console.log('     file write success');


        console.log(' <- response provided');


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

                            $ , cordova.file.dataDirectory + 'speech.wav', options, true).then(
                              function (FileEntry) {
                                console.debug('>>> Success', FileEntry);
                                var filePath = cordova.file.dataDirectory + 'speech.wav';
                              function (error) {
                                console.debug('>>> download failure', error);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download