首页 文章

运行时出现Google Speech API React-Native错误

提问于
浏览
0

尝试将Google语音转换为文本API到React-Native . 这是我到目前为止的代码 . 我得到的错误是:“捆绑失败:错误:

无法从/Users/Desktop/finalTest/final3/App.js解析模块fs:Haste模块映射中不存在模块fs“ .

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

清晰的守望者 Watch :守望者 Watch - 所有 . 删除node_modules文件夹:rm -rf node_modules && npm install . 重置Metro Bundler缓存:rm -rf / tmp / metro-bundler-cache- *或npm start - --reset-cache . 删除急速缓存:rm -rf / tmp / haste-map-react-native-packager- * .

任何帮助,将不胜感激 .

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

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

    如果您需要文件系统访问,那么您将需要第三方库,例如react-native-fs

相关问题