# 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
[](https://badge.fury.io/js/react-native-speech-engine)
[](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 ? '正在监听...' : '未监听'}
实时识别:
{partialText}
最终结果:
{recognizedText}
文本转语音
状态: {isSpeaking ? '正在朗读...' : '未朗读'}
);
};
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`
开始语音识别。
**参数:**
- `options` (可选): 配置对象
- `locale` (string): 语言代码,例如 'zh-CN'、'en-US',默认为 'en-US'
- `partialResults` (boolean): 是否返回部分结果,默认为 false
- `maxResults` (number): 最大返回结果数,可选
**返回:** `Promise`
#### `stopSpeechRecognition(): Promise`
停止语音识别并返回最终识别结果。
**返回:** `Promise` - 识别的文本
#### `cancelSpeechRecognition(): Promise`
取消语音识别,不返回结果。
**返回:** `Promise`
#### `isSpeechRecognitionAvailable(): Promise`
检查语音识别是否可用。
**返回:** `Promise` - 是否可用
### 文本转语音方法
#### `speak(text: string, options: TextToSpeechOptions): Promise`
将文本转换为语音并播放。
**参数:**
- `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`
#### `stop(): Promise`
停止语音播放。
**返回:** `Promise`
#### `pause(): Promise`
暂停语音播放。
**返回:** `Promise`
#### `resume(): Promise`
继续语音播放。
**返回:** `Promise`
#### `isSpeaking(): Promise`
检查是否正在播放语音。
**返回:** `Promise` - 是否正在播放
### 事件监听方法
#### 语音识别事件
- `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!