2

I am trying to use Watson text to speech service in a javascript code. However, I am stuck trying to get it working.

If I use the following code:

 $.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();
                }
            });

I get:

Failed to load https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Please note that I could easily get a request like this is working from Restlet.

However, if I use:

$.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();
                        }
                });

I get:

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.
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Moni
  • 869
  • 3
  • 9
  • 21

1 Answers1

1

It looks like IBM Watson Text To Speech does support partially CORS (needed in your case). Please check that answer : Can't access IBM Watson API locally due to CORS on a Rails/AJAX App

Also, you'll find a wise advice there that informs you not to add your Watson credentials in your JavaScript code, and rather use tokens : https://console.bluemix.net/docs/services/watson/getting-started-tokens.html#tokens-for-authentication

As you're working on the client side, maybe trying out Watson's NPM module or libraries (with example) would be a good choice :

https://www.npmjs.com/package/watson-speech

https://watson-speech.mybluemix.net/text-to-speech.html

Hope this helps!

Philippe Sultan
  • 2,111
  • 17
  • 23