首页 > 解决方案 > 如何将 Google Cloud 文本上传到语音 API 对 Cloud Storage [Node.js] 的响应

问题描述

我使用 Node.js 服务器制作了一个简单的音频创建 Web 应用程序。我想使用云文本到语音 API 创建音频,然后将该音频上传到云存储。

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

这是 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直接上传到云存储的方法。所以,如果你有提示,请告诉我。先感谢您。

标签: node.jsgoogle-cloud-platformgoogle-cloud-storagegoogle-text-to-speech

解决方案


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

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

...
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);
     });
...

实现此部分后,您将下载保存在本地的文件并准备好上传。我建议您更好地查看我提到的另一篇文章,以防您对如何实现它有更多疑问。

让我知道这些信息是否对您有帮助!


推荐阅读