如何实现语音react
语音识别与React集成
在React应用中实现语音识别功能,可以通过浏览器提供的Web Speech API或第三方库。Web Speech API包含SpeechRecognition接口,允许开发者将语音转换为文本。
安装必要的依赖(如使用第三方库):
npm install react-speech-recognition
基本实现步骤
创建一个React组件并导入语音识别库:

import React, { useState } from 'react';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
const VoiceComponent = () => {
const [message, setMessage] = useState('');
const { transcript, resetTranscript } = useSpeechRecognition();
if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
return <div>浏览器不支持语音识别</div>;
}
const startListening = () => {
SpeechRecognition.startListening({ continuous: true, language: 'zh-CN' });
};
return (
<div>
<button onClick={startListening}>开始录音</button>
<button onClick={SpeechRecognition.stopListening}>停止</button>
<button onClick={resetTranscript}>重置</button>
<p>{transcript}</p>
</div>
);
};
export default VoiceComponent;
自定义语音命令
通过react-speech-recognition可以定义语音命令,触发特定操作:
const commands = [
{
command: '打开 *',
callback: (website) => setMessage(`尝试打开: ${website}`)
},
{
command: '重置',
callback: () => resetTranscript()
}
];
const { transcript } = useSpeechRecognition({ commands });
语音合成(文本转语音)
使用Web Speech API的SpeechSynthesis接口实现文本朗读:

const speak = (text) => {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'zh-CN';
window.speechSynthesis.speak(utterance);
};
// 在组件中使用
<button onClick={() => speak('欢迎使用语音功能')}>朗读文本</button>
跨浏览器兼容性处理
不同浏览器对Web Speech API的支持程度不同,建议添加检测逻辑:
const isSupported =
'SpeechRecognition' in window ||
'webkitSpeechRecognition' in window;
if (!isSupported) {
// 提供备选方案或提示
}
性能优化建议
对于长时间语音输入场景,建议分段处理识别结果。可以设置continuous: false并定期重新启动识别,避免内存泄漏。实时显示识别内容时,使用防抖技术减少渲染频率。
const { transcript } = useSpeechRecognition({
continuous: false,
interimResults: true
});






