React-Native Ошибка Google Speech API при запуске - PullRequest
0 голосов
/ 26 октября 2018

Попытка переместить API Google Speech to text в React-Native.Это код, который у меня есть до сих пор.Я получаю следующее сообщение об ошибке: «сбой объединения: ошибка:

Не удается разрешить модуль fs из /Users/Desktop/finalTest/final3/App.js: модуль fs не существует в карте модулей Haste».

Я попытался запустить предложенные команды, но они все еще не работали:

  1. Очистить часы сторожа: watchman watch-del-all.
  2. Удалить папку node_modules: rm -rf node_modules && npm install.
  3. Сброс кеша Metro Bundler: rm -rf /tmp/metro-bundler-cache-* или npm start -- --reset-cache.
  4. Удалить кэш скорости: 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 голосов
/ 26 октября 2018

Вы не можете использовать fs или какие-либо модули ядра узла в этом отношении в реагировать нативно. Подробнее об этом можно прочитать здесь , но лучше всего думать, что ваш JS - это чистый JavaScript без каких-либо добавленных API или модулей.

Если вам нужен доступ к файловой системе, тогда вам понадобитсясторонняя библиотека, например react-native-fs

...