Thomas David Kehoe
Thomas David Kehoe

Reputation: 10940

Using IBM Watson Text-to-Speech with Firebase Cloud Functions?

I'm trying to use set up a Firebase Cloud Function to access IBM Watson Text-to-Speech. The problem is writing the returned audiofile to my Firestore database.

This test to return the list of voices worked, logging the response to the Functions log:

exports.test = functions.firestore.document('IBM_Watson_Token/Test_Value').onUpdate((change, context) => {
  var textToSpeech = new TextToSpeechV1({
    username: 'groucho',
    password: 'swordfish'
  });

  return textToSpeech.listVoices(null, function(error, voices) {
    if (error) {
      console.log(error);
    } else {
      console.log(JSON.stringify(voices, null, 2));
    }
  });
});

Here is the documentation example Node code for returning an audiofile and writing it to the server:

var TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');
var fs = require('fs');

var textToSpeech = new TextToSpeechV1({
  username: '{username}',
  password: '{password}'
});

var synthesizeParams = {
  text: 'Hello world',
  accept: 'audio/wav',
  voice: 'en-US_AllisonVoice'
};

// Pipe the synthesized text to a file.
textToSpeech.synthesize(synthesizeParams).on('error', function(error) {
  console.log(error);
}).pipe(fs.createWriteStream('hello_world.wav'));

Firebase doesn't allow writing files to the server using fs, you have to write to a Firestore database. I changed the last line of the example code to write to Firestore, using a promise:

exports.test = functions.firestore.document('IBM_Watson_Token/Test_Value').onUpdate((change, context) => {
  var textToSpeech = new TextToSpeechV1({
    username: 'groucho',
    password: 'swordfish'
  });

  var synthesizeParams = {
    text: 'Hello world',
    accept: 'audio/wav',
    voice: 'en-US_AllisonVoice'
  };

    return textToSpeech.synthesize(synthesizeParams).on('error', function(error) {
    console.log(error);
  }).then(function (audiofile) {
    admin.firestore().collection('IBM_Watson_Token').doc('hello_world').set({
      'audiofile': audiofile
    })
  })
  .catch(function (error) {
    console.log(error);
  });
});

The error message was

TypeError: textToSpeech.synthesize(...).on(...).then is not a function

How do I save the audiofile that comes back from Watson to Firestore?

Upvotes: 0

Views: 404

Answers (1)

chughts
chughts

Reputation: 4737

That would be because the synthesize method is not returning a promise. You will need to use a callback construct that looks like

    textToSpeech.synthesize(params, function (err, body, response) {
      if (err) {
        ...
      } else {
        // body is the audio
        ... 
      }
    });

Upvotes: 1

Related Questions