You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

React Native Expo CLI环境下如何实现Speech-to-text功能?

Speech-to-Text in React Native Expo: Working Solutions

Hey there! I totally get the frustration of hunting for speech-to-text libraries that play nice with Expo—let’s walk through the most reliable ways to implement this feature without breaking your Expo workflow.

Expo has a first-party library built specifically for speech recognition, which is the easiest and most compatible option. Here’s how to set it up:

Step 1: Install the library

Run this command in your project directory:

npx expo install expo-speech-recognition

Step 2: Configure Permissions

Add the required permissions to your app.json or app.config.js to request access to the microphone and speech recognition services:

{
  "expo": {
    "ios": {
      "infoPlist": {
        "NSSpeechRecognitionUsageDescription": "We need access to your speech recognition to convert your voice to text.",
        "NSMicrophoneUsageDescription": "We need access to your microphone to record your voice."
      }
    },
    "android": {
      "permissions": [
        "RECORD_AUDIO",
        "INTERNET" // Required for cloud-based recognition
      ]
    }
  }
}

Step 3: Implement the Recognition Logic

Here’s a simple example component to handle speech-to-text:

import React, { useState, useEffect } from 'react';
import { View, Button, Text, Alert } from 'react-native';
import * as SpeechRecognition from 'expo-speech-recognition';

export default function SpeechToTextComponent() {
  const [isListening, setIsListening] = useState(false);
  const [recognizedText, setRecognizedText] = useState('');

  useEffect(() => {
    async function requestPermissions() {
      const { status } = await SpeechRecognition.requestPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('Permission Denied', 'We need microphone and speech recognition permissions to work.');
      }
    }
    requestPermissions();
  }, []);

  const startListening = async () => {
    if (!isListening) {
      try {
        await SpeechRecognition.startListeningAsync({
          language: 'en-US', // Adjust to your target language
          onResult: (result) => {
            setRecognizedText(result.transcription);
          },
        });
        setIsListening(true);
      } catch (error) {
        Alert.alert('Error', 'Failed to start listening: ' + error.message);
      }
    }
  };

  const stopListening = async () => {
    await SpeechRecognition.stopListeningAsync();
    setIsListening(false);
  };

  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 18, marginBottom: 20 }}>Recognized Text: {recognizedText}</Text>
      <Button
        title={isListening ? 'Stop Listening' : 'Start Listening'}
        onPress={isListening ? stopListening : startListening}
      />
    </View>
  );
}

2. Integrate Native Libraries with EAS Build (For Advanced Use Cases)

If you need features like offline speech recognition that the official Expo library doesn’t support, you can use a native library like react-native-voice. Note that this won’t work with Expo Go—you’ll need to use EAS Build to create a custom development client or production build.

Step 1: Install the Library

npm install react-native-voice

Step 2: Configure Permissions

Add the same permissions to your app.json as mentioned above. For iOS, you may also need to enable the Speech Recognition capability in your EAS build config (add this to eas.json if needed):

{
  "build": {
    "development": {
      "ios": {
        "capabilities": {
          "speechRecognition": true
        }
      }
    }
  }
}

Step 3: Build with EAS

Run this command to create a custom development client:

eas build --profile development --platform ios/android

Once the build is done, install it on your device and test the integration.

Key Notes to Keep in Mind

  • Language Support: Make sure to specify the correct language code (e.g., es-ES for Spanish, fr-FR for French) based on your users’ needs.
  • Cloud vs. Offline: Most speech recognition services (including Expo’s) rely on cloud processing, so ensure your app has internet access. For offline support, look into libraries that offer on-device models (like react-native-voice with certain configurations).
  • User Experience: Always clearly explain why you need permissions, and handle cases where permissions are denied gracefully.

内容的提问来源于stack exchange,提问作者Muhammad Zumair

火山引擎 最新活动