React项目实现语音转文字后,如何将文字转换为谷歌助理风格语音?
React项目文字转语音(TTS)实现方案
你已经完成语音转文字的开发后,可以通过以下两种方案实现文字转音频输出,可匹配谷歌助理的音色风格:
方案1:使用浏览器原生Web Speech API(无额外依赖)
无需安装任何第三方包,直接调用浏览器内置的speechSynthesis接口即可实现,轻量且适配绝大多数现代浏览器,调整参数后可以贴近目标音色效果,参考实现代码如下:
import { useCallback, useState } from 'react'; // 封装TTS自定义hook const useTextToSpeech = () => { const [isPlaying, setIsPlaying] = useState(false); const speak = useCallback((text: string) => { // 先停止之前正在播放的语音,避免重复触发报错 window.speechSynthesis.cancel(); const utterance = new SpeechSynthesisUtterance(text); // 基础参数调整,匹配谷歌助理发声风格 utterance.lang = 'zh-CN'; // 中文场景使用,英文场景可替换为en-US utterance.rate = 0.95; // 语速,1为系统默认,谷歌助理语速稍慢 utterance.pitch = 1.05; // 音调,1为系统默认,谷歌助理音调稍高 utterance.volume = 1; // 音量范围0-1 // 匹配系统内置的谷歌类音色 const voices = window.speechSynthesis.getVoices(); const targetVoice = voices.find(voice => voice.name.includes('Google') || voice.name.includes('Assistant') ); if (targetVoice) utterance.voice = targetVoice; // 状态同步 utterance.onstart = () => setIsPlaying(true); utterance.onend = () => setIsPlaying(false); window.speechSynthesis.speak(utterance); }, []); const stop = useCallback(() => { window.speechSynthesis.cancel(); setIsPlaying(false); }, []); return { speak, stop, isPlaying }; }; // 业务组件调用示例 const App = () => { const { speak, isPlaying } = useTextToSpeech(); // transcribedText为你之前语音转文字得到的结果 const transcribedText = "这里是语音转文字得到的文本内容"; return ( <div> <p>识别结果:{transcribedText}</p> <button onClick={() => speak(transcribedText)} disabled={isPlaying}> {isPlaying ? '播放中' : '转为谷歌助理音色播放'} </button> </div> ); };
方案2:使用React专用TTS库(功能更丰富)
如果原生API的配置灵活度、跨端一致性满足不了需求,可以选择和你现有语音转文字模块适配度较高的React TTS库,集成逻辑和你现有代码的契合度很高,不需要做太多额外的兼容处理。
核心注意点
- 离线场景优先选择原生Web Speech API,不需要发起网络请求即可使用
- 如果需要高度还原谷歌助理的官方音色,可以直接调用谷歌官方TTS接口,将返回的音频流通过audio标签播放即可
内容的提问来源于stack exchange,提问作者naoval luthfi
相关产品推荐
相关产品推荐

