简体   繁体   中英

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. 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?

"await" is used for async function, let's put your code into a async 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.

What you could to is wrap part of the code in a promise function and then callign that 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

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

I don't understand why it's an unexpected identifier. Wasn't const client created?

The answer is that, yes, const client was initialised but await is not treated as a keyword in ordinary JavaScript scripts. 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.

To use await as an operator it must be coded in an async function or generator. Using await as an identifier in new code is probably unwise.

Background:

  • ES5.1 did not have await as a reserved or future reserved word,
  • ES6 (ECMAScript 2015) introduced await as a future reserved word in the context of an ECMAScript module.
  • 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

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.

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

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM