首页 > 解决方案 > 对云函数的 Javascript 请求

问题描述

我正在尝试使用 Google Speech to Text API,因此我正在尝试在云函数(云函数 API)中实现它。问题是我想从一个 javascript 文件中调用该函数,该文件正在为创建语音生成订单的网站的一部分运行代码。那么我有3个问题:

· 不知道怎么调用URL,同时发送函数需要的参数。我猜是一个帖子。数据类似于:

const data = {
    audio: base64AudioFormat,
    lan: language
}

· 然后在云功能中,我不知道如何修改谷歌给出的代码,所以它在这种情况下工作。给出的代码是这样的:

// Imports the Google Cloud client library
const fs = require('fs');
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

const config = {
  encoding: LINEAR16,
  sampleRateHertz: 16000,
  languageCode: (my 'lan' parameter from data),
};
const audio = {
  content: (my 'base64AudioFormat' parameter from data),
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file
const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log('Transcription: ', transcription);

· 最后我想接收API 在我的javascript 文件中返回的字符串。我猜是GET。

我会很感激任何帮助!

标签: javascriptgoogle-cloud-platformgoogle-speech-to-text-api

解决方案


我使用您的代码在云功能中使用。此云功能将接受带有数据的请求 { "audio": "base64 format data", "lan": "en-US"}。请求参数将被放入 intreq.body.audio并且req.body.lan您现在可以在代码中使用它们。

为了进行测试,我使用了从语音到文本的快速入门中的示例数据。云功能使用 Node.js14。

index.js:

exports.speechToText = async (req, res) => {

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

const encoding = 'LINEAR16';
const sampleRateHertz = 16000;

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: req.body.lan,
};

const audio = {
  content: req.body.audio,
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file
const [response] = await client.recognize(request);
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log('Transcription: ', transcription);

  res.status(200).send(transcription);
};

包.json:

{
  "dependencies": {
    "@google-cloud/speech": "^4.5.1"
  },
  "name": "sample-http",
  "version": "0.0.1"
}

这是我在云函数中测试代码时的请求和响应: 在此处输入图像描述

如果您想查看触发函数的不同方式,请参阅云函数触发器。


推荐阅读