运行时,Google Speech API React-Native错误

时间:2018-10-25 23:32:09

标签: node.js reactjs react-native google-speech-api

试图将Google Speech to text API移至React-Native。这是我到目前为止的代码。我得到的错误是:“捆绑失败:错误:

  

无法从fs解析模块/Users/Desktop/finalTest/final3/App.js:急速模块图中不存在模块fs

我尝试运行建议的命令,但仍然无法正常工作:

  
      
  1. 清晰的值班员手表:watchman watch-del-all。      
        
    1. 删除node_modules文件夹:rm -rf node_modules && npm install
    2.   
    3. 重置Metro Bundler缓存:rm -rf /tmp/metro-bundler-cache-*npm start -- --reset-cache
    4.   
    5. 删除急速缓存:rm -rf /tmp/haste-map-react-native-packager-*
    6.   
  2.   

任何帮助将不胜感激。

import React, { Component } from "react";
import { Platform, StyleSheet, Text, View } from "react-native";
import axios from "axios";

const instructions = Platform.select({
  ios: "Press Cmd+R to reload,\n" + "Cmd+D or shake for dev menu",
  android:
    "Double tap R on your keyboard to reload,\n" +
    "Shake or press menu button for dev menu"
});

const fs = require("fs");
const axios = require("axios");

const API_KEY = "./keyfile.json";
const fileName = "./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
};

const apiKey = API_KEY;
const url = `https://speech.googleapis.com/v1/speech:recognize?key=${apiKey}`;

axios
  .request({
    url,
    method: "POST",
    data: request
  })
  .then(response => {
    const transcription = response.data.results
      .map(result => result.alternatives[0].transcript)
      .join("\n");
    console.log(`Transcription: ${transcription}`);
  })
  .catch(err => {
    console.log("err :", err);
  });

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});

1 个答案:

答案 0 :(得分:0)

您不能在本机反应中使用fs或任何节点核心模块。 You can read more about that here,但最好将您的JS视为纯JavaScript,而不添加任何API或模块。

如果需要文件系统访问权限,则需要第三方库,例如react-native-fs