如何通过Google文本语音API(fs.writeFile与createWriteStream)将文件写入Firebase存储?

时间:2018-12-21 23:04:01

标签: node.js firebase google-cloud-platform firebase-storage text-to-speech

我正在尝试将Google Cloud Text-to-Speech API音频文件写入Firebase存储。 Node.js documentation显示了如何使用fs.writeFile写入本地文件,但是我认为我需要使用其他内容,也许是file.writefilefs.createWriteStream

我将documentation示例修改为写入Firebase存储的Firebase Cloud函数:

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();

  }
});

错误消息是:

TypeError: path must be a string or Buffer
    at fs.writeFile (fs.js:1277:6)

这是问题所在所在的行中的参数file

await writeFile(file, response.audioContent, 'binary');

根据documentation,该参数必须是字符串,Buffer,URL或整数。我给了它一个功能。我的猜测是我需要使用fs.writeFile以外的其他东西。也许fs.createWriteStream?还是应该将fs.writeFile更改为file.writeFile

还有,为什么Google Cloud Text-to-Speech API documentation使用await而没有async

0 个答案:

没有答案