I'm trying to write a Google Cloud Text-to-Speech API audio file to Firebase Storage. The Node.js documentation shows how to write to a local file using fs.writeFile but I think I need to use something else, perhaps file.writefile or fs.createWriteStream.
I modified the documentation example as a Firebase Cloud Function writing to Firebase Storage:
exports.Google_T2S = functions.firestore.document('Users/{userID}/Spanish/T2S_Request').onUpdate((change, context) => {
if (change.after.data().word != undefined) {
const word = change.after.data().word;
const longLanguage = 'Spanish';
const audioFormat = '.mp3';
const fs = require('fs');
const util = require('util');
const textToSpeech = require('@google-cloud/text-to-speech'); // Imports the Google Cloud client library
const client = new textToSpeech.TextToSpeechClient(); // Creates a client
const text = word; // The text to synthesize
let myWordFile = word.replace(/ /g,"_"); // replace spaces with underscores in the file name
myWordFile = myWordFile.toLowerCase(); // convert the file name to lower case
myWordFile = myWordFile + audioFormat; // append .mp3 to the file name;
// boilerplate copied from https://cloud.google.com/blog/products/gcp/use-google-cloud-client-libraries-to-store-files-save-entities-and-log-data
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('myApp.appspot.com');
const file = bucket.file('Audio/' + longLanguage + '/' + myWordFile);
const request = { // Construct the request
input: {text: text},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'es-ES', ssmlGender: 'FEMALE'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
async function test() {
try {
// Performs the Text-to-Speech request
const [response] = await client.synthesizeSpeech(request);
// Write the binary audio content to a local file
const writeFile = util.promisify(fs.writeFile);
await writeFile(file, response.audioContent, 'binary');
console.log('Audio content written to file: output.mp3');
} catch (error) {
console.error(error);
}
}
test();
}
});
The error message is:
TypeError: path must be a string or Buffer
at fs.writeFile (fs.js:1277:6)
This is saying that the problem is the parameter file in the line
await writeFile(file, response.audioContent, 'binary');
According to the documentation, that parameter must be a string, Buffer, URL, or integer. I gave it a function. My guess is that I need to use something other than fs.writeFile. Perhaps fs.createWriteStream? Or should I change fs.writeFile to file.writeFile?
Also, why does the Google Cloud Text-to-Speech API documentation use await without async?