React Native 中语音到文本转换的问题

问题描述 投票:0回答:1

我在各种库和功能中遇到了语音转文本功能的问题。尽管尝试了论坛、网站和人工智能驱动方法中的多种解决方案,但我无法在我的 React Native 项目中成功实现语音到文本功能。

我尝试集成不同的库,例如 @react-native-voice/voice、react-native-community/voice、react-native-voicebox-speech-rec、react-native-speech-to-text 等。我遵循了有关 app.json 和 AndroidManifest 中的权限、metroConfig 中的配置等的建议。然而,当在ExpoGo中运行代码时,它会抛出一个错误,表明startSpeech无法识别。在使用 EAS 进行构建时,此错误会消失,但在按下开始录制按钮时,它会激活麦克风而不产生任何文本输出。我希望将语音输入转录为文本,但没有显示任何文本。

如果对此问题有任何建议或解决方案,我将不胜感激。谢谢你。

react-native expo speech-to-text react-native-community react-native-voice
1个回答
0
投票
import React, { useState, useEffect } from "react";
import { View, Alert, TextInput, TouchableOpacity } from "react-native";
import Voice from "@react-native-voice/voice";
import ComponentStyles from "../styles/ComponentStyles";
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { useAppContext } from "../context/AppContext";

export default function SpeechToText({ text, setText }) {
  const { styles, color } = ComponentStyles();
  const [isListening, setIsListening] = useState(false);
  const { showToast } = useAppContext()

  useEffect(() => {
    function onSpeechResults(e) {
      const recognizedText = e.value.join(' ');
      setText(prevText => `${prevText} ${recognizedText}`);
      showToast("Texto reconocido", recognizedText);
    }

    function onSpeechError(errorCode) {
      showToast("Error", `Código de error: ${errorCode}`);
    }

    Voice.onSpeechError = onSpeechError;
    Voice.onSpeechResults = onSpeechResults;

    return function cleanup() {
      Voice.destroy().then(Voice.removeAllListeners);
    };
  }, [isListening]);

  async function toggleListening() {
    try {
      if (isListening) {
        if (await Voice.isRecognizing()) {
          await Voice.stop();
          setIsListening(false);
        }
      } else {
        await Voice.start('en-US');
        setIsListening(true);
      }
    } catch (e) {
      showToast("Error", e);
    }
  }

  return (
    <View style={styles.container}>
      <View style={styles.inputSpeechContainer}>
        <View style={styles.inputSpeech}>
          <TextInput
            style={styles.input}
            placeholderTextColor={color}
            onChangeText={(e) => setText(e)}
            value={text}
            placeholder="Ingrese una descripción"
            multiline
            numberOfLines={5}
          />
        </View>
        <TouchableOpacity onPress={toggleListening} style={{ alignSelf: 'flex-end' }}>
          <MaterialCommunityIcons name={isListening ? 'stop-circle-outline' : 'microphone'} color={color} size={22} />
        </TouchableOpacity>
      </View>
    </View>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.