node.js和Google云工具中的一名业余爱好者。我已采用此代码来尝试从Google Cloud存储桶中转录一段音频。当我在终端中运行node index.js
时,我只得到 SyntaxError:await仅在异步函数中有效。我意识到这意味着我需要一个异步功能。但是,如何将整个文件转换为可以从终端成功运行的命令?
// 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 = 'gs://anitomaudiofiles/911isnojoke.mp3';
const encoding = 'MP3';
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}`);
答案 0 :(得分:1)
您不能在异步函数之外编写await operation.promise()
。如果要使用await,则应在函数内部。
(async runOperations() {
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}`);
})();
您可以将其放入文件中,然后运行node <filename.js>
来运行它。
答案 1 :(得分:0)
只需将其放在异步函数中即可
// earlier code here
async function main() {
const [operation] = await client.longRunningRecognize(request);
const [response] = await operation.promise();
const transcription = response.results
.map(result => result.alternatives[0].transcript)
.join('\n');
console.log(`Transcription: ${transcription}`);
}
main()