如何上传 Google Cloud text to speech API 对 Cloud Storage [Node.js] 的回复

How to upload Google Cloud text to speech API's response to Cloud Storage [Node.js]

我使用 Node.js 服务器制作了一个简单的音频创建网络应用程序。我想使用 Cloud text to speech API 创建音频,然后将该音频上传到 Cloud storage。

(我为 Linux、Debian 10.3 和 Google Chrome 浏览器使用 Windows 10、Windows 子系统。)

这是 Node.js 服务器中的代码。

const client = new textToSpeech.TextToSpeechClient();
        async function quickStart() {

            // The text to synthesize
            const text = 'hello, world!';

            // Construct the request
            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'},
            };

            // Performs the text-to-speech request
            const [response] = await client.synthesizeSpeech(request);
            // Write the binary audio content to a local file
            console.log(response);

我想上传 response 到云存储。

我可以直接上传 response 到云存储吗?或者我是否必须将 response 保存在 Node.js 服务器中并将其上传到云存储?

我在网上搜索了一下,没找到直接上传response到云存储的方法。所以,如果你有什么提示,请告诉我。提前谢谢你。

您应该能够做到这一点,所有代码都在同一个文件中。实现这一目标的最佳方法是使用 Cloud Function,它将文件发送到您的 Cloud Storage。 但是,是的,您需要使用 Node.js 保存您的文件,然后,您将把它上传到 Clou Storage。

为此,您需要将文件保存在本地,然后将其上传到云存储。由于您可以在另一个 post 中查看完整教程,因此您需要构建文件,将其保存在本地,然后上传。以下代码是您需要在代码中添加的主要部分。

...
const options = { // construct the file to write
     metadata: {
          contentType: 'audio/mpeg',
          metadata: {
              source: 'Google Text-to-Speech'
          }
     }
};

// copied from https://cloud.google.com/text-to-speech/docs/quickstart-client-libraries#client-libraries-usage-nodejs
const [response] = await client.synthesizeSpeech(request);
// Write the binary audio content to a local file
// response.audioContent is the downloaded file
     return await file.save(response.audioContent, options)
     .then(() => {
         console.log("File written to Firebase Storage.")
         return;
     })
     .catch((error) => {
         console.error(error);
     });
...

一旦您实施了这部分,您将下载保存在本地的文件并准备好上传。我建议你好好看看另一个post我,以防你对如何实现它有更多的疑问。

如果这些信息对您有帮助,请告诉我!