I've built a function that detects whenever a txt file is uploaded to Firebase Storage and creates and audio file (mp3) using the Google Cloud Text-To-Speech API.
First:
Add this dependency in the package.json
"@google-cloud/text-to-speech": "^3.2.2"
And here's the code:
const fs = require('fs');
const util = require('util');
exports.textToSpeech = functions.region('europe-west1').storage.object().onFinalize(async (object) => {
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const bucket = admin.storage().bucket(fileBucket);
// Imports the Google Cloud client library
const textToSpeech = require('@google-cloud/text-to-speech');
// Creates a client
const client = new textToSpeech.TextToSpeechClient();
// Exit if the image is already a thumbnail.
if ( filePath.endsWith(".txt") ) {
const filename = filePath.replace( ".txt" , ".mp3" );
return bucket.file(filePath).download( async (err, contents) => {
if (err) {
console.log('error', err);
return null
}
const text = contents.toString(); // Text inside the txt file
try{
const request = {
input: {text: text},
// Select the language and SSML voice gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
const [response] = await client.synthesizeSpeech(request);
const writeFile = util.promisify(fs.writeFile);
await writeFile('/tmp/output.mp3', response.audioContent, 'binary');
await bucket.upload('/tmp/output.mp3', {
destination: filename
});
}catch(err) {
console.log( "ERROR: "+err );
}
});
}else{
return 0;
}
});