google.cloud.speech.v1.RecognizeRequest.audio: 当我传递对象时期望的对象

google.cloud.speech.v1.RecognizeRequest.audio: object expected when I passed the object

我尝试在我的 node.js 项目中使用 google 云语音来发短信。我遵循了文档中的快速启动指南。我传递了 wav 和 flac 格式的音频文件,但在这两种情况下我都收到错误消息:error TypeError: .google.cloud.speech.v1.RecognizeRequest.audio: object expected

            try {
              const speech = require('@google-cloud/speech');
              const client = new speech.SpeechClient();
              const filename = require('path').join(__dirname + '/../temp/test.wav');

              const config = {
                encoding: 'LINEAR16',
                sampleRateHertz: 16000,
                languageCode: 'en-US'
              };
              const audio = fs.readFileSync(filename).toString('base64');
              const request = {
                config: config,
                audio: audio
              };
              const [response] = await client.recognize(request);
              const transcription = response.results
                .map(result => result.alternatives[0].transcript)
                .join('\n');
              console.log(`Transcription: ${transcription}`);

如您所见,请求是一个对象,当我 consoled.log 它被正确转换为字符串时。但是函数 client.recognize 不起作用。您认为问题出在哪里?

request 中的 audio 属性 需要是一个对象,其中 audioBytes 作为 属性 称为 content,如下例所示:

// Reads a local audio file and converts it to base64
const audioBytes = fs.readFileSync(fileName).toString('base64');

// The audio file's encoding, sample rate in hertz, and BCP-47 language code
const audio = {
  content: audioBytes,
};

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