使用在服务器上生成的 AccessToken 连接到 GCP Text to Speech

Using generated on the server AccessToken to connect to GCP Text to Speech

我希望能够使用服务器上生成的访问令牌从 react.js 前端连接到 GCP Text to Speech。我改编了 中的代码以生成访问令牌。但是,我无法在文档中找到如何使用该令牌从前端连接到 GCP。

为简单起见,我想从修改文档中的 the linked working node.js example 开始,以使用硬编码访问令牌而不是默认凭据文件来连接服务。

这里是我的尝试(相对于example,只修改了client的构造):

'use strict';

function main() {
  // [START tts_quickstart]
  // Imports the Google Cloud client library
  const textToSpeech = require('@google-cloud/text-to-speech');

  // Import other required libraries
  const fs = require('fs');
  const util = require('util');
  // Creates a client
  const client = new textToSpeech({tk: 'ya29.c.Kp8BCQj<etc.>'}).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
    const writeFile = util.promisify(fs.writeFile);
    await writeFile('output.mp3', response.audioContent, 'binary');
    console.log('Audio content written to file: output.mp3');
  }
  quickStart();
  // [END tts_quickstart]
}

main(...process.argv.slice(2));

我收到一条错误消息,指出 textToSpeech 不是构造函数。如何修复此示例以使用访问令牌连接到 GCP Text to Speech?

遗憾的是,无法使用文本转语音 Nodejs 客户端库通过访问令牌进行身份验证。 Node 运行时中的 TextToSpeechClient 仅接受可从服务帐户中找到的凭据对象。

根据您在问题中包含的 ,它生成访问令牌并在 Android 中使用它。这是有道理的,因为目前 Android 还没有客户端库,因此 OP 正在使用文本转语音 REST API 创建 HTTP 请求。使用 HTTP 请求需要 access token 认证,SO 例子的解决方案。

我的建议如下:

  1. 采用类似于的解决方案,通过HTTP发送请求,以便您可以使用访问令牌进行身份验证。
  2. 使用不同的编程语言,例如 Python(似乎不太可能,因为您使用的是 React)。有可能 in Python Client Library to use access token for authentication since it accepts credentials object.

还要补充一点,您在客户端对象上传递的参数不正确。应该是const client = new textToSpeech.TextToSpeechClient(object);