简体   繁体   English

谷歌语音转文本 API 示例代码将无法运行

[英]Google speech-to-text API sample code will not run

I've been constantly rereading the instructions (setting up the project, setting the environmental variable to the file path of the JSON file with my service account key, installing/initializing gcloud etc.) but I just can't run the sample code at all and I can't figure out why.我一直在重新阅读说明(设置项目,使用我的服务帐户密钥将环境变量设置为 JSON 文件的文件路径,安装/初始化 gcloud 等)但我无法运行示例代码所有,我不知道为什么。 The sample code is:示例代码是:

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
const gcsUri = '.resources/audio.raw';
const encoding = 'LINEAR16';
const sampleRateHertz = 16000;
const languageCode = 'en-US';

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

const audio = {
  uri: gcsUri,
};

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

// Detects speech in the audio file. This creates a recognition job that you
// can wait for now, or get its result later.
const [operation] = await client.longRunningRecognize(request);
// Get a Promise representation of the final result of the job
const [response] = await operation.promise();
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: ${transcription}`);

Terminal says the following error:终端显示以下错误:

const [operation] = await client.longRunningRecognize(request);
                      ^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

I don't understand why it's an unexpected identifier.我不明白为什么它是一个意外的标识符。 Wasn't const client created?没有创建 const 客户端吗?

"await" is used for async function, let's put your code into a async function “await”用于异步 function,让我们将您的代码放入异步 function

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
const gcsUri = '.resources/audio.raw';
const encoding = 'LINEAR16';
const sampleRateHertz = 16000;
const languageCode = 'en-US';

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

const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};
async function main () {
// Detects speech in the audio file. This creates a recognition job that you
// can wait for now, or get its result later.
const [operation] = await client.longRunningRecognize(request);
// Get a Promise representation of the final result of the job
const [response] = await operation.promise();
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: ${transcription}`);
}
main();

The await keyword can only be used in functions that are asynchronous. await关键字只能在异步函数中使用。

What you could to is wrap part of the code in a promise function and then callign that promise:您可以将部分代码包装在 promise function 中,然后调用 promise:

const detectSpeach = async () => {
  // Detects speech in the audio file. This creates a recognition job that you
  // can wait for now, or get its result later.
  const [operation] = await client.longRunningRecognize(request);
  // Get a Promise representation of the final result of the job
  const [response] = await operation.promise();
  const transcription = response.results
    .map(result => result.alternatives[0].transcript)
    .join('\n');
  console.log(`Transcription: ${transcription}`);
};

detectSpeach();

more on this: https://javascript.info/async-await更多信息: https://javascript.info/async-await

const [operation] = await client.longRunningRecognize(request);
                  ^^^^^^
SyntaxError: Unexpected identifier

I don't understand why it's an unexpected identifier.我不明白为什么它是一个意外的标识符。 Wasn't const client created?没有创建const client吗?

The answer is that, yes, const client was initialised but await is not treated as a keyword in ordinary JavaScript scripts.答案是,是的, const client已初始化,但await在普通 JavaScript 脚本中不被视为关键字。 Outside of an async function (or generator function), await is usually a valid identifier, so the sequence of await followed by client is not a valid expression because client is an unexpected identifier.async function(或生成器函数)之外, await通常是一个有效的标识符,因此client后面的await序列不是有效的表达式,因为client是一个意外的标识符。

To use await as an operator it must be coded in an async function or generator.要将await用作运算符,它必须在async function 或生成器中编码。 Using await as an identifier in new code is probably unwise.在新代码中使用await作为标识符可能是不明智的。

Background:背景:

  • ES5.1 did not have await as a reserved or future reserved word, ES5.1 没有await作为保留字或未来保留字,
  • ES6 (ECMAScript 2015) introduced await as a future reserved word in the context of an ECMAScript module. ES6 (ECMAScript 2015) 在 ECMAScript 模块的上下文中引入了await作为未来的保留字。
  • ECMAScript 2019 includes await as a reserved word but provides it can be used as an identifier unless the goal [symbol] of the syntactic grammar is Module ECMAScript 2019 包含await作为保留字,但提供它可以用作标识符,除非句法语法的目标 [symbol] 是Module

My understanding of this patchwork mess is that both await and async are detected by modifying the JavaScript parser to detect what would have been syntax errors ( async function , await identifier , for await... of ) and process them further in some, but not all, contexts.我对这种拼凑的混乱的理解是,通过修改 JavaScript 解析器来检测可能是什么语法错误( async async functionawait await identifierfor await... of )并在某些情况下进一步处理它们,而不是进一步处理它们所有,上下文。

Writing an answer since I don't have enough reputation to comment.写一个答案,因为我没有足够的声誉来发表评论。 Which node version are you using?您使用的是哪个节点版本? IIRC, await / async is supported since version 7.6 IIRC,从 7.6 版开始支持await / async

Other answers talk about putting it in an async function, you need to do that too but I think the error it throws for that case would be something along the line of "async is a reserved keyword".其他答案谈论将其放入async function 中,您也需要这样做,但我认为它为这种情况引发的错误将类似于“异步是保留关键字”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 显示Google Cloud语音转文字 - Displaying Google Cloud Speech-to-Text Node.js中的Google Cloud语音到文本api编码问题 - Google Cloud Speech-to-Text api encoding issues in Node.js 谷歌Chrome语音到文本API连续不起作用? - Google Chrome Speech-to-Text API JavaScript Continuous Doesn't Work? 语音到文本识别不准确 - Speech-to-text Recognition is not accurate 如何优雅地结束 Google Speech-to-Text 流识别并取回待处理的文本结果? - How to end Google Speech-to-Text streamingRecognize gracefully and get back the pending text results? 针对盲人的JavaScript语音转文本 - JavaScript Speech-to-Text for blind people Google Cloud Speech-to-Text 无法在某些 iDevice 上正确转录流式音频 - Google Cloud Speech-to-Text doesn't transcribe streamed audio correctly on some iDevices 如何将本地html5录制的音频的float32Array格式转换为Google语音转文本服务的适当字节? - How to convert the float32Array format of native html5 recorded audio to proper bytes for Google Speech-to-Text service? Google翻译API文字转语音 - Google Translate API text-to-speech 在Microsoft BotFramework WebChat中集成用于文本到语音和语音到文本的认知语音服务 - Integrating Cognitive Speech Service for both Text-to-Speech and Speech-to-Text in Microsoft BotFramework WebChat
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM