在 React-Native 上实现 Google Cloud 语音转文本

Gus*_*avo 2 speech-to-text react-native google-speech-api

我正在尝试在本机反应应用程序上实现谷歌的语音到文本,但我找不到有关它的示例或文档,我对反应本机相当陌生,所以我有点迷失了,有一个使用的示例谷歌官方文档上的node.js,我试图将其“复制”到react-native,但我没有取得任何成功。

这是 Node.js 示例:

async function main() {
  // Imports the Google Cloud client library
  const speech = require('@google-cloud/speech');
  const fs = require('fs');

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

  // The name of the audio file to transcribe
  const fileName = './resources/audio.raw';

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

  // The audio file's encoding, sample rate in hertz, and BCP-47 language code
  const audio = {
    content: audioBytes,
  };
  const config = {
    encoding: 'LINEAR16',
    sampleRateHertz: 16000,
    languageCode: 'en-US',
  };
  const request = {
    audio: audio,
    config: config,
  };

  // Detects speech in the audio file
  const [response] = await client.recognize(request);
  const transcription = response.results
    .map(result => result.alternatives[0].transcript)
    .join('\n');
  console.log(`Transcription: ${transcription}`);
}
main().catch(console.error);
Run Code Online (Sandbox Code Playgroud)

首先,“fs”包不适用于react-native,所以我必须使用具有不同功能的“react-native-fs”

其次,我真的应该使用“require”来调用语音包吗?我猜反应原生会使用“导入”来代替,对吗?

关于如何在 React-Native 上实现它有什么建议吗?谢谢!

小智 5

您无法在 React Native 上运行 @google-cloud/speech,因为 RN 在 JV 环境中运行,而库 (@google-cloud/speech) 在 Nodejs 环境中运行。您可以创建一个 api 并部署它,或者使用此库react-native-google-speech-api