首页 > 解决方案 > 在 Firebase Cloud Functions 中使用 Google Cloud Speech to Text

问题描述

Google Cloud Speech to Text文档规定您可以通过以下方式访问它:

const client = new speech.SpeechClient();

const [operation] = await client.longRunningRecognize({
  config: {
    encoding: 'LINEAR16',
    sampleRateHertz: 16000,
    languageCode: 'en-US'
  },
  audio: {
    uri: `gs://${bucket}/${name}`
  }
});

const [response] = await operation.promise();

response.results.forEach(result => {
  console.log(`Transcription: ${result.alternatives[0].transcript}`);
});

现在,我想在 Firebase Cloud Function 中运行此代码。不幸的是,Cloud Functions 在尚不支持asyncawait功能的 Node 版本上运行。

我尝试过的一些事情:

  1. 尝试 TypeScript,它支持asyncawait:我使用的其他一些 API 遇到了一堆问题。
  2. 将我所有的功能升级到节点 8(测试版),它支持asyncawait:再次,在 Firebase 方面遇到了相当多的错误。
  3. 手动“翻译”代码(这甚至是一件事吗?):我试图让代码期待一个承诺。

这也不太好用,看起来是这样的:

exports.onStorageObjectFinalize = functions.storage.object()
  .onFinalize((object) => {
  const client = new speech.SpeechClient();

  return client.longRunningRecognize({
    config: {
      encoding: 'LINEAR16',
      sampleRateHertz: 16000,
      languageCode: 'en-US'
    },
    audio: {
      uri: `gs://${object.bucket}/${object.name}`
    }
  })
  .then(r1 => {
    const [operations] = r1;

    return operations.promise();
  })
  .then(r2 => {
    const [response] = r2;

    // response.results...

    return true;
  });
});

编辑:当上述函数运行时,它说没有operations.promise(). 事实上,看整个operations物体后,结构看起来并不像它的功能一样。我确实发现 中有一个promise属性operations._callOptions,所以我尝试返回operations._callOptions.promise(),但出现了一个奇怪的错误:TypeError: #<CallSettings> is not a promise at client.longRunningRecognize.then.r1.

我是不是把翻译代码弄乱了,或者这无论如何都行不通?我可以尝试其他任何事情,或者 TypeScript 和 Node 8 是我唯一的两个选择吗?

谢谢,非常感谢。

标签: firebasegoogle-cloud-platformasync-awaitgoogle-cloud-functionsspeech-to-text

解决方案


推荐阅读