npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-native-speech-engine

v0.0.1

Published

React Native Speech Recognition and Text-to-Speech with new architecture support

Downloads

3

Readme

React Native Speech Engine

npm version License: MIT

一个支持新架构(New Architecture)的React Native语音识别和文本转语音库。

特性

  • 🎤 语音识别(Speech-to-Text)
  • 🔊 文本转语音(Text-to-Speech)
  • 🚀 支持React Native新架构(Fabric和Turbo Modules)
  • 🌍 支持多语言
  • 📱 支持iOS和Android平台
  • 🔄 提供部分识别结果和最终识别结果
  • ⏯️ 支持暂停、继续和停止语音播放

安装

1. 安装包

npm install react-native-speech-engine

或使用yarn:

yarn add react-native-speech-engine

2. iOS 额外步骤

cd ios && pod install

3. Android 权限配置

android/app/src/main/AndroidManifest.xml 中添加权限:

<!-- 语音识别所需权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

4. iOS 权限配置

ios/项目名称/Info.plist 中添加以下配置:

<key>NSMicrophoneUsageDescription</key>
<string>此应用需要访问麦克风以进行语音识别</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>此应用需要使用语音识别功能</string>

使用方法

导入库

import SpeechEngine from 'react-native-speech-engine';

语音识别

// 开始语音识别
try {
  await SpeechEngine.startSpeechRecognition({
    locale: 'zh-CN', // 设置语言,默认为 'en-US'
    partialResults: true, // 是否返回部分结果,默认为false
    maxResults: 5 // 最大返回结果数,可选
  });
} catch (error) {
  console.error('启动语音识别失败:', error);
}

// 停止语音识别并获取最终结果
try {
  const result = await SpeechEngine.stopSpeechRecognition();
  console.log('识别结果:', result);
} catch (error) {
  console.error('停止语音识别失败:', error);
}

// 取消语音识别(不返回结果)
try {
  await SpeechEngine.cancelSpeechRecognition();
} catch (error) {
  console.error('取消语音识别失败:', error);
}

// 检查语音识别是否可用
const isAvailable = await SpeechEngine.isSpeechRecognitionAvailable();
console.log('语音识别可用性:', isAvailable);

文本转语音

// 文本转语音
try {
  await SpeechEngine.speak('你好,世界!', {
    language: 'zh-CN', // 设置语言,默认为 'en-US'
    pitch: 1.0, // 音调,范围0.5-2.0,默认1.0
    rate: 1.0, // 语速,范围0.5-2.0,默认1.0
    volume: 1.0 // 音量,范围0-1,默认1.0
  });
} catch (error) {
  console.error('文本转语音失败:', error);
}

// 停止语音播放
try {
  await SpeechEngine.stop();
} catch (error) {
  console.error('停止语音失败:', error);
}

// 暂停语音播放
try {
  await SpeechEngine.pause();
} catch (error) {
  console.error('暂停语音失败:', error);
}

// 继续语音播放
try {
  await SpeechEngine.resume();
} catch (error) {
  console.error('继续语音失败:', error);
}

// 检查是否正在播放语音
const isSpeaking = await SpeechEngine.isSpeaking();
console.log('是否正在播放语音:', isSpeaking);

事件监听

// 语音识别事件监听
SpeechEngine.onSpeechRecognitionStart(() => {
  console.log('语音识别已开始');
});

SpeechEngine.onSpeechRecognitionEnd(() => {
  console.log('语音识别已结束');
});

SpeechEngine.onSpeechRecognitionResults((results) => {
  console.log('语音识别结果:', results);
  // results是一个数组,每个元素包含以下属性:
  // - transcript: 识别的文本
  // - confidence: 置信度 (0-1)
  // - isFinal: 是否为最终结果
});

SpeechEngine.onSpeechRecognitionError((error) => {
  console.error('语音识别错误:', error);
  // error包含以下属性:
  // - code: 错误代码
  // - message: 错误消息
});

// 文本转语音事件监听
SpeechEngine.onTextToSpeechStart(() => {
  console.log('文本转语音已开始');
});

SpeechEngine.onTextToSpeechFinish(() => {
  console.log('文本转语音已完成');
});

SpeechEngine.onTextToSpeechError((error) => {
  console.error('文本转语音错误:', error);
});

// 清理所有监听器
SpeechEngine.removeAllListeners();

完整示例

import React, { useState, useEffect } from 'react';
import { View, Text, Button, StyleSheet, Alert, PermissionsAndroid, Platform } from 'react-native';
import SpeechEngine from 'react-native-speech-engine';

const SpeechExample = () => {
  const [isListening, setIsListening] = useState(false);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [recognizedText, setRecognizedText] = useState('');
  const [partialText, setPartialText] = useState('');

  useEffect(() => {
    // 请求Android权限
    if (Platform.OS === 'android') {
      requestPermissions();
    }

    // 设置事件监听器
    setupEventListeners();

    return () => {
      // 清理监听器
      SpeechEngine.removeAllListeners();
    };
  }, []);

  const requestPermissions = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
        {
          title: '麦克风权限',
          message: '应用需要访问麦克风来进行语音识别',
          buttonNeutral: '稍后询问',
          buttonNegative: '取消',
          buttonPositive: '确定',
        }
      );

      if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
        Alert.alert('权限被拒绝', '需要麦克风权限才能使用语音识别功能');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  const setupEventListeners = () => {
    // 语音识别事件
    SpeechEngine.onSpeechRecognitionStart(() => {
      setIsListening(true);
      setPartialText('');
    });

    SpeechEngine.onSpeechRecognitionEnd(() => {
      setIsListening(false);
    });

    SpeechEngine.onSpeechRecognitionResults((results) => {
      if (results && results.length > 0) {
        const result = results[0];
        if (result.isFinal) {
          setRecognizedText(result.transcript);
          setPartialText('');
        } else {
          setPartialText(result.transcript);
        }
      }
    });

    SpeechEngine.onSpeechRecognitionError((error) => {
      setIsListening(false);
      Alert.alert('语音识别错误', error.message);
    });

    // 文本转语音事件
    SpeechEngine.onTextToSpeechStart(() => {
      setIsSpeaking(true);
    });

    SpeechEngine.onTextToSpeechFinish(() => {
      setIsSpeaking(false);
    });

    SpeechEngine.onTextToSpeechError((error) => {
      setIsSpeaking(false);
      Alert.alert('文本转语音错误', error);
    });
  };

  const startListening = async () => {
    try {
      await SpeechEngine.startSpeechRecognition({
        locale: 'zh-CN',
        partialResults: true
      });
    } catch (error) {
      Alert.alert('错误', '无法开始语音识别');
    }
  };

  const stopListening = async () => {
    try {
      await SpeechEngine.stopSpeechRecognition();
    } catch (error) {
      console.error('停止语音识别失败:', error);
    }
  };

  const speakText = async () => {
    try {
      if (!recognizedText) {
        Alert.alert('提示', '没有可朗读的文本');
        return;
      }
      await SpeechEngine.speak(recognizedText, {
        language: 'zh-CN',
        pitch: 1.0,
        rate: 1.0
      });
    } catch (error) {
      Alert.alert('错误', '无法朗读文本');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>语音引擎示例</Text>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>语音识别</Text>
        <Text>状态: {isListening ? '正在监听...' : '未监听'}</Text>
        
        <View style={styles.buttonRow}>
          <Button
            title={isListening ? '正在监听...' : '开始识别'}
            onPress={startListening}
            disabled={isListening}
          />
          <Button
            title='停止识别'
            onPress={stopListening}
            disabled={!isListening}
          />
        </View>
        
        <View style={styles.resultContainer}>
          <Text style={styles.label}>实时识别:</Text>
          <Text style={styles.partialText}>{partialText}</Text>
          
          <Text style={styles.label}>最终结果:</Text>
          <Text style={styles.recognizedText}>{recognizedText}</Text>
        </View>
      </View>
      
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>文本转语音</Text>
        <Text>状态: {isSpeaking ? '正在朗读...' : '未朗读'}</Text>
        
        <Button
          title={isSpeaking ? '正在朗读...' : '朗读识别结果'}
          onPress={speakText}
          disabled={isSpeaking || !recognizedText}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
  },
  section: {
    backgroundColor: 'white',
    padding: 15,
    borderRadius: 8,
    marginBottom: 20,
    elevation: 2,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginVertical: 10,
  },
  resultContainer: {
    marginTop: 15,
  },
  label: {
    fontWeight: 'bold',
    marginTop: 10,
  },
  partialText: {
    fontStyle: 'italic',
    color: '#666',
    minHeight: 20,
  },
  recognizedText: {
    fontWeight: '500',
    minHeight: 20,
  },
});

export default SpeechExample;

API 文档

语音识别方法

startSpeechRecognition(options: SpeechRecognitionOptions): Promise<void>

开始语音识别。

参数:

  • options (可选): 配置对象
    • locale (string): 语言代码,例如 'zh-CN'、'en-US',默认为 'en-US'
    • partialResults (boolean): 是否返回部分结果,默认为 false
    • maxResults (number): 最大返回结果数,可选

返回: Promise<void>

stopSpeechRecognition(): Promise<string>

停止语音识别并返回最终识别结果。

返回: Promise<string> - 识别的文本

cancelSpeechRecognition(): Promise<void>

取消语音识别,不返回结果。

返回: Promise<void>

isSpeechRecognitionAvailable(): Promise<boolean>

检查语音识别是否可用。

返回: Promise<boolean> - 是否可用

文本转语音方法

speak(text: string, options: TextToSpeechOptions): Promise<void>

将文本转换为语音并播放。

参数:

  • text (string): 要转换为语音的文本
  • options (可选): 配置对象
    • language (string): 语言代码,例如 'zh-CN'、'en-US',默认为 'en-US'
    • pitch (number): 音调,范围 0.5-2.0,默认为 1.0
    • rate (number): 语速,范围 0.5-2.0,默认为 1.0
    • volume (number): 音量,范围 0-1,默认为 1.0

返回: Promise<void>

stop(): Promise<void>

停止语音播放。

返回: Promise<void>

pause(): Promise<void>

暂停语音播放。

返回: Promise<void>

resume(): Promise<void>

继续语音播放。

返回: Promise<void>

isSpeaking(): Promise<boolean>

检查是否正在播放语音。

返回: Promise<boolean> - 是否正在播放

事件监听方法

语音识别事件

  • onSpeechRecognitionStart(callback: () => void): EventSubscription

    • 语音识别开始时触发
  • onSpeechRecognitionEnd(callback: () => void): EventSubscription

    • 语音识别结束时触发
  • onSpeechRecognitionResults(callback: (results: SpeechRecognitionResult[]) => void): EventSubscription

    • 收到语音识别结果时触发
    • results 是一个数组,每个元素包含:
      • transcript: 识别的文本
      • confidence: 置信度 (0-1)
      • isFinal: 是否为最终结果
  • onSpeechRecognitionError(callback: (error: SpeechRecognitionError) => void): EventSubscription

    • 语音识别发生错误时触发
    • error 包含:
      • code: 错误代码
      • message: 错误消息

文本转语音事件

  • onTextToSpeechStart(callback: () => void): EventSubscription

    • 文本转语音开始时触发
  • onTextToSpeechFinish(callback: () => void): EventSubscription

    • 文本转语音完成时触发
  • onTextToSpeechError(callback: (error: string) => void): EventSubscription

    • 文本转语音发生错误时触发

清理方法

  • removeAllSpeechRecognitionListeners(): void

    • 移除所有语音识别事件监听器
  • removeAllTextToSpeechListeners(): void

    • 移除所有文本转语音事件监听器
  • removeAllListeners(): void

    • 移除所有事件监听器

支持的语言

语音识别和文本转语音支持多种语言,以下是常用的语言代码:

  • zh-CN - 中文(简体)
  • en-US - 英语(美国)
  • ja-JP - 日语
  • ko-KR - 韩语
  • fr-FR - 法语
  • de-DE - 德语
  • es-ES - 西班牙语

注意:实际支持的语言可能因设备和平台而异。

常见问题

Q: 在Android上无法使用语音识别?

A: 请确保已添加必要的权限到 AndroidManifest.xml 文件中,并且在运行时请求了 RECORD_AUDIO 权限。

Q: 在iOS上无法使用语音识别?

A: 请确保已添加必要的权限到 Info.plist 文件中,并且已运行 pod install

Q: 如何在新架构中使用此库?

A: 此库已支持React Native新架构(Fabric和Turbo Modules),无需额外配置。在React Native 0.80.0及以上版本中,新架构是默认启用的。

许可证

MIT License

贡献

欢迎提交Issue和Pull Request!