gpt4 book ai didi

node.js - 在 Express 服务器中使用 Google Speech API

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:21 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的网络应用程序,它使用 Google Speech API 将音频文件转录为文本。我正确设置了 Google Speech API 身份验证等,因此我设法运行 Google 的 Node 示例。现在我想从我自己的服务器上一个名为“audio.raw”的本地文件调用它,该文件与以下 server.js 位于同一目录中:

const express = require("express");
const fs = require("fs");
const app = express();
app.set("port", process.env.PORT || 3001);

function syncRecognize (filename, encoding, sampleRateHertz, languageCode) {

const Speech = require('@google-cloud/speech');
const speech = Speech();

const request = {
encoding: encoding,
sampleRateHertz: sampleRateHertz,
languageCode: languageCode
};

speech.recognize(filename, request)
.then((results) => {
const transcription = results[0];
return transcription;
})
.catch((err) => {
console.error('ERROR:', err);
});
}

app.get("/api/transcribe", (req, res) => {

syncRecognize(
'./audio.raw',
'LINEAR16',
16000,
'en-US'
).then(text => {res.json(text)})
.catch((err) => {
console.error('ERROR:', err);
});
})

当我尝试执行此操作时,出现以下错误:

[0] TypeError: Cannot read property 'then' of undefined
[0] at /path/to/server.js:62:4 // the .then after syncRecognize(...)
...

我需要做哪些不同的事情?

编辑

好的,我验证了syncRecognize 函数确实在某个时刻返回了正确的const 转录。问题是由于某种原因 .then 不会等待它返回。

我读到,为了使用“.then”运算符,您需要返回一个 promise 。我不太确定如何做到这一点或是否有更好的选择。我想这确实是我对异步缺乏了解的问题。

最佳答案

我们可以在函数的最后几行看到方法调用 recognize() 确实返回 Promise 。您可以通过使用 f .then().catch()

轻松判断

由于您在 app.get() 中将此方法作为 Promise 调用,因此只需在您的方法中返回 Promise:

const Speech = require('@google-cloud/speech')
const speech = Speech()

function syncRecognize (filename, encoding, sampleRateHertz, languageCode) {

const request = {
encoding,
sampleRateHertz,
languageCode,
}

return speech.recognize(filename, request)
}

关于node.js - 在 Express 服务器中使用 Google Speech API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com