几个月前,这在我的 websocket 服务器内部没有代码更改的情况下工作,但是今天使用它,似乎 Google 语音到文本 api 不再允许使用访问令牌进行身份验证。
这是我以前的工作方法,直到今天遇到这个错误
const client = new speech.SpeechClient({
access_token: ACCESS_TOKEN,
projectId: 'project-name'
});
这让我出现了标题中的上述错误。
我还尝试通过如下设置环境来切换到服务帐户(我过去使用过)
export GOOGLE_APPLICATION_CREDENTIALS="path-to-key.json"
然后我在没有上述代码的情况下运行客户端,而是运行:
const client = new speech.SpeechClient();
这给我带来了这个美丽的错误,即使此时环境是使用项目 ID 设置的
Error: Unable to detect a Project Id in the current environment.
任何解决此问题的帮助将不胜感激!
我通过执行以下操作解决了环境问题和随后的错误:
const options = {
keyFilename: 'path-to-key.json',
projectId: 'project-name',
};
const client = new speech.SpeechClient(options);
我能够按照官方快速入门进行操作,并使用客户端库使其正常工作,没有出现任何问题。我将在下面解释我所做的事情。
来自 云语音转文本 - 快速入门:
gcloud config set project YOUR_PROJECT_NAME
gcloud services enable speech.googleapis.com
gcloud iam service-accounts create [SA-NAME] \
--description "[SA-DESCRIPTION]" \
--display-name "[SA-DISPLAY-NAME]"
gcloud iam service-accounts keys create ~/key.json \
--iam-account [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com
GOOGLE_APPLICATION_CREDENTIALS
设置为包含服务帐户密钥的 JSON 文件的文件路径:export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
npm install --save @google-cloud/speech
quickstart.js
文件并将以下代码示例放入其中: 'use strict';
// [START speech_quickstart]
async function main() {
// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');
const fs = require('fs');
// Creates a client
const client = new speech.SpeechClient();
// The name of the audio file to transcribe
const fileName = './resources/audio.raw';
// Reads a local audio file and converts it to base64
const file = fs.readFileSync(fileName);
const audioBytes = file.toString('base64');
// The audio file's encoding, sample rate in hertz, and BCP-47 language code
const audio = {
content: audioBytes,
};
const config = {
encoding: 'LINEAR16',
sampleRateHertz: 16000,
languageCode: 'en-US',
};
const request = {
audio: audio,
config: config,
};
// 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}");
}
main().catch(console.error);
WHERE
const fileName = './resources/audio.raw'
是您的 test.raw 音频所在的路径。