Home > Mobile >  Google apps script: response "audioContent" from GCP text-to-speech coming back as text fi
Google apps script: response "audioContent" from GCP text-to-speech coming back as text fi

Time:09-17

I'm using google apps script to invoke text-to-speech in GCP. I get a response but it is in text format as opposed to a mp3. How do I save it as a mp3?

Here is the code:

function gcp_text_to_speech(){
  var payload = {
  'input':{
    'text':'I\'ve added the event to your calendar.'
  },
  'voice':{
    'languageCode':'en-gb',
    'name':'en-GB-Standard-A',
    'ssmlGender':'FEMALE'
  },
  'audioConfig':{
    'audioEncoding':'MP3'
  }
};

  var response = UrlFetchApp.fetch(
    "https://texttospeech.googleapis.com/v1/text:synthesize", {
      method: "POST",
      headers: {
        "Authorization" : "Bearer "   getService().getAccessToken()
      },
      contentType: "application/json",
      payload: JSON.stringify(payload),
      muteHttpExceptions: true
    });  

  var mp3 = response.getBlob()
  var res = Drive.Files.insert({title: ".mp3"}, mp3)

}

I don't see any audio options in getAs(contentType). Is it possible?

All these don't work. I have tried:

response.getBlob('audioContent')
response.getContent('audioContent')
JSON.parse(response).audioContent.getBlob()
response.getBlob(JSON.parse(response).audioContent)
response.getAs('audio/mpeg')
response.getAs('mp3')

CodePudding user response:

Decode your base64 string response, then create a blob out of it. then insert the file to drive.

var decoded = Utilities.base64Decode(JSON.parse(response).audioContent, Utilities.Charset.UTF_8);
var blob = Utilities.newBlob(decoded, 'audio/mpeg', "output.mp3");
var res = Drive.Files.insert({'title': 'test.mp3', 'mimeType': 'audio/mpeg'}, mp3)
  • Related