探索Alan AI:为React Native赋予语音智能
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import Speech from '@react-native-community/speech';
export default function App() {
const [isSpeaking, setIsSpeaking] = useState(false);
const startSpeaking = () => {
if (!isSpeaking) {
Speech.speak({
text: '你好,世界!',
language: 'zh-CN',
onStart: () => setIsSpeaking(true),
onFinish: () => setIsSpeaking(false),
onError: (e) => Alert.alert('发生错误', e.error)
});
}
};
const stopSpeaking = () => {
if (isSpeaking) {
Speech.stop();
setIsSpeaking(false);
}
};
return (
<View style={styles.container}>
<Button title="开始" onPress={startSpeaking} disabled={isSpeaking} />
<Button title="停止" onPress={stopSpeaking} disabled={!isSpeaking} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
});
这段代码展示了如何在React Native应用中使用@react-native-community/speech
库来实现文本转语音(TTS)功能。代码中定义了startSpeaking
和stopSpeaking
函数来控制语音播报的开始和停止,并通过按钮交互来触发这些函数。同时,代码使用了React Hook useState
来管理组件的状态。
评论已关闭