首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用React Native的Google Cloud speech

使用React Native的Google Cloud speech
EN

Stack Overflow用户
提问于 2017-02-27 23:27:52
回答 2查看 1.5K关注 0票数 5

我正在尝试使用Google Cloud Speech API,这样我就可以传递音频文件并接收翻译后的文本,但我坚持使用集成。我已经有了api密钥和所有需要的东西,但是找不到如何在react原生中使用它。在文档中只有对node.js的解释(来自javascript部分)。此外,有几个库已经过时或只支持一个操作系统。有人成功做到了吗?

文档中的node.js示例:

代码语言:javascript
运行
复制
// Imports the Google Cloud client library
const Speech = require('@google-cloud/speech');

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const speechClient = Speech({
  projectId: projectId
});

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

// The audio file's encoding and sample rate
const options = {
  encoding: 'LINEAR16',
  sampleRate: 16000
};

// Detects speech in the audio file
speechClient.recognize(fileName, options)
  .then((results) => {
    const transcription = results[0];
    console.log(`Transcription: ${transcription}`);
  });
EN

回答 2

Stack Overflow用户

发布于 2019-03-26 14:29:23

您可以使用google app engine部署代码,并从react-native发出post请求。还需要配置和使用谷歌云存储来存储转换的音频文件。这是我的服务器代码。

代码语言:javascript
运行
复制
const format = require('util').format;
const fs = require('fs');
const express = require('express');
const multer  = require('multer');
const requestHttp = require('request');
const {Storage} = require('@google-cloud/storage');

// Instantiate a storage client
const storage = new Storage();

// const upload = multer();
const app = express();

// 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 encoding = 'LINEAR16';
const sampleRateHertz = 16000;
const languageCode = 'en-US';

  const upload = multer({
    storage: multer.memoryStorage(),
    limits: {
      fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
    },
  });

  const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);


app.post('/upload', upload.single('file') , async (req, res) => {

    const file = await req.file
    if (!file) {
      const error = new Error('Please upload a file')
      error.httpStatusCode = 400
      return next(error)
    }

    // Create a new blob in the bucket and upload the file data.
    const blob = bucket.file(req.file.originalname);
    const blobStream = blob.createWriteStream({
      resumable: false,
    });

    blobStream.on('error', err => {
      next(err);
    });

    blobStream.on('finish', async () => {
        // The public URL can be used to directly access the file via HTTP.
        const publicUrl = await format(
          `https://storage.googleapis.com/${bucket.name}/${blob.name}`
        );
        const request = {
            config: {
              encoding: encoding,
              sampleRateHertz: sampleRateHertz,
              languageCode: languageCode,
            },
            audio: {
                uri: 'gs://YOUR-Bucket-Name/File-name.ext'
            } 
          };
        // Stream the audio to the Google Cloud Speech API
        const [response] = await client.recognize(request);
        const transcription = response.results
          .map(result => result.alternatives[0].transcript)
          .join('\n');
        console.log(`Transcription: `, transcription);
        res.status(200)
            .send({
            success: 'true',
            message: 'Text retrieved successfully',
            text: transcription
            })
            .end();

      });
      blobStream.end(req.file.buffer);
});


const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
票数 1
EN

Stack Overflow用户

发布于 2017-10-16 23:22:42

将此服务器部署到Heroku,然后从您的react原生应用程序向此服务器发送post或get请求,并在您的应用程序上获得结果。使用Axios库https://github.com/axios/axios发送post或get请求

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42489512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档