# react-native-speech-engine **Repository Path**: isyhj/react-native-speech-engine ## Basic Information - **Project Name**: react-native-speech-engine - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-08-27 - **Last Updated**: 2025-08-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # React Native Speech Engine [![npm version](https://badge.fury.io/js/react-native-speech-engine.svg)](https://badge.fury.io/js/react-native-speech-engine) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 一个支持新架构(New Architecture)的React Native语音识别和文本转语音库。 ## 特性 - 🎤 语音识别(Speech-to-Text) - 🔊 文本转语音(Text-to-Speech) - 🚀 支持React Native新架构(Fabric和Turbo Modules) - 🌍 支持多语言 - 📱 支持iOS和Android平台 - 🔄 提供部分识别结果和最终识别结果 - ⏯️ 支持暂停、继续和停止语音播放 ## 安装 ### 1. 安装包 ```bash npm install react-native-speech-engine ``` 或使用yarn: ```bash yarn add react-native-speech-engine ``` ### 2. iOS 额外步骤 ```bash cd ios && pod install ``` ### 3. Android 权限配置 在 `android/app/src/main/AndroidManifest.xml` 中添加权限: ```xml ``` ### 4. iOS 权限配置 在 `ios/项目名称/Info.plist` 中添加以下配置: ```xml NSMicrophoneUsageDescription 此应用需要访问麦克风以进行语音识别 NSSpeechRecognitionUsageDescription 此应用需要使用语音识别功能 ``` ## 使用方法 ### 导入库 ```javascript import SpeechEngine from 'react-native-speech-engine'; ``` ### 语音识别 ```javascript // 开始语音识别 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); ``` ### 文本转语音 ```javascript // 文本转语音 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); ``` ### 事件监听 ```javascript // 语音识别事件监听 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(); ``` ### 完整示例 ```javascript 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 ( 语音引擎示例 语音识别 状态: {isListening ? '正在监听...' : '未监听'}