javascript - 对云函数的 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。
我会很感激任何帮助!
解决方案
我使用您的代码在云功能中使用。此云功能将接受带有数据的请求 { "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"
}
如果您想查看触发函数的不同方式,请参阅云函数触发器。
推荐阅读
- python - 如何将标签的文本位置移动到标签图像 Tkinter 上方
- python - AttributeError:“NoneType”对象没有属性“reshape”,然后另一个错误没有属性“values”“resize”
- asp.net - ASP.NET Core 2.2 使用 Office 365 发送电子邮件
- python - 为什么 inspect() 认为 map 不是内置的?
- sql - 如何识别日期在哪个季度|Oracle SQL |
- python-3.x - 如何使用python中的python-docx模块在docx文件中添加eps图像
- sql - SQL:当一列有最大/计数子查询时,我可以编写多列查询吗?
- java - java内存泄漏的原因
- function - Tkinter - 使用功能更改标签
- wordpress - 我在我的wordpress网站上使用花哨的盒子,在那个标题中使用默认的h2标签,我怎么能把那个h2标签改成h1标签