如何用JS原生实现文字转语音?无需插件的完整指南

一、核心API:Web Speech API的SpeechSynthesis接口

Web Speech API是W3C标准化的浏览器原生接口,其中SpeechSynthesis模块专门用于文本转语音(TTS)。该接口自Chrome 33、Firefox 49、Edge 79及Safari 14起全面支持,无需任何前置安装。

1.1 基础实现代码

  1. function speakText(text) {
  2. // 创建新的语音合成实例
  3. const synthesis = window.speechSynthesis;
  4. // 创建语音内容对象
  5. const utterance = new SpeechSynthesisUtterance(text);
  6. // 执行语音合成
  7. synthesis.speak(utterance);
  8. }
  9. // 调用示例
  10. speakText("欢迎使用JavaScript原生文字转语音功能");

这段代码通过三步完成核心功能:获取合成器实例、创建包含文本的语音对象、触发播放。

1.2 语音参数配置

SpeechSynthesisUtterance对象支持多种参数配置:

  1. const utterance = new SpeechSynthesisUtterance("配置示例");
  2. utterance.lang = 'zh-CN'; // 设置中文语言
  3. utterance.rate = 1.2; // 语速(0.1-10)
  4. utterance.pitch = 1.5; // 音高(0-2)
  5. utterance.volume = 0.8; // 音量(0-1)
  6. utterance.voice = voices.find(v => v.lang === 'zh-CN'); // 指定语音

二、语音库管理

2.1 获取可用语音列表

浏览器内置的语音库可通过speechSynthesis.getVoices()获取:

  1. function loadVoices() {
  2. const voices = window.speechSynthesis.getVoices();
  3. console.log("可用语音列表:", voices);
  4. // 动态更新语音选择(某些浏览器异步加载)
  5. window.speechSynthesis.onvoiceschanged = loadVoices;
  6. }
  7. loadVoices();

典型输出包含语音名称、语言、性别等属性,中文环境通常包含微软Huihui、Yaoyao等语音。

2.2 语音选择策略

建议实现语音选择逻辑:

  1. function selectVoice(lang = 'zh-CN', gender = 'female') {
  2. const voices = window.speechSynthesis.getVoices();
  3. return voices.find(v =>
  4. v.lang.includes(lang) &&
  5. (gender === 'any' || v.voiceURI.includes(gender))
  6. );
  7. }

三、高级功能实现

3.1 暂停/恢复控制

  1. const synthesis = window.speechSynthesis;
  2. let currentUtterance;
  3. function speakWithControl(text) {
  4. synthesis.cancel(); // 清除之前的语音
  5. currentUtterance = new SpeechSynthesisUtterance(text);
  6. synthesis.speak(currentUtterance);
  7. }
  8. function pauseSpeech() {
  9. synthesis.pause();
  10. }
  11. function resumeSpeech() {
  12. synthesis.resume();
  13. }

3.2 语音事件监听

  1. const utterance = new SpeechSynthesisUtterance("事件示例");
  2. utterance.onstart = () => console.log("开始播放");
  3. utterance.onend = () => console.log("播放结束");
  4. utterance.onerror = (e) => console.error("错误:", e);
  5. utterance.onboundary = (e) => console.log("到达边界:", e.charIndex);

四、兼容性处理方案

4.1 浏览器检测

  1. function isSpeechSynthesisSupported() {
  2. return 'speechSynthesis' in window;
  3. }
  4. if (!isSpeechSynthesisSupported()) {
  5. alert("您的浏览器不支持文字转语音功能,请使用Chrome/Firefox/Edge最新版");
  6. }

4.2 移动端适配

移动设备需要用户交互触发语音:

  1. document.getElementById('speakBtn').addEventListener('click', () => {
  2. speakText("移动端需要点击触发");
  3. });

五、实际应用场景

5.1 无障碍阅读器

  1. class AccessibilityReader {
  2. constructor(element) {
  3. this.element = element;
  4. this.init();
  5. }
  6. init() {
  7. this.element.addEventListener('click', () => {
  8. const text = this.element.textContent;
  9. speakText(text);
  10. });
  11. }
  12. }
  13. // 使用示例
  14. new AccessibilityReader(document.getElementById('article'));

5.2 多语言学习工具

  1. function pronounceWord(word, lang) {
  2. const utterance = new SpeechSynthesisUtterance(word);
  3. utterance.lang = lang; // 如'en-US', 'fr-FR'
  4. window.speechSynthesis.speak(utterance);
  5. }

六、性能优化建议

  1. 语音缓存:重复文本可复用SpeechSynthesisUtterance对象
  2. 内存管理:及时调用speechSynthesis.cancel()清除队列
  3. 异步处理:对长文本进行分块处理(每块≤200字符)
  4. 错误重试:实现指数退避重试机制

七、完整示例:带UI控制的语音播放器

  1. <div id="tts-controller">
  2. <textarea id="text-input" rows="5" cols="50">输入要转换的文字</textarea>
  3. <select id="voice-select"></select>
  4. <button onclick="speak()">播放</button>
  5. <button onclick="pauseSpeech()">暂停</button>
  6. <button onclick="resumeSpeech()">继续</button>
  7. <button onclick="synthesis.cancel()">停止</button>
  8. </div>
  9. <script>
  10. const synthesis = window.speechSynthesis;
  11. let currentUtterance;
  12. function loadVoices() {
  13. const voiceSelect = document.getElementById('voice-select');
  14. const voices = synthesis.getVoices();
  15. voiceSelect.innerHTML = voices
  16. .filter(v => v.lang.includes('zh') || v.lang.includes('en'))
  17. .map(v => `<option value="${v.voiceURI}">${v.name} (${v.lang})</option>`)
  18. .join('');
  19. }
  20. function speak() {
  21. const text = document.getElementById('text-input').value;
  22. const voiceURI = document.getElementById('voice-select').value;
  23. const voices = synthesis.getVoices();
  24. const voice = voices.find(v => v.voiceURI === voiceURI);
  25. synthesis.cancel();
  26. currentUtterance = new SpeechSynthesisUtterance(text);
  27. currentUtterance.voice = voice;
  28. synthesis.speak(currentUtterance);
  29. }
  30. // 初始化
  31. loadVoices();
  32. window.speechSynthesis.onvoiceschanged = loadVoices;
  33. </script>

八、常见问题解决方案

  1. 语音不可用:检查浏览器是否支持,更新至最新版本
  2. 中文语音缺失:确保系统安装了中文语音包(Windows需安装中文语言包)
  3. 移动端无声:确认在用户交互事件中触发,且设备音量已打开
  4. Safari兼容性:需在HTTPS环境下或localhost开发环境使用

通过以上技术实现,开发者可以完全基于浏览器原生能力构建功能完善的文字转语音系统,适用于教育、无障碍、语音交互等多个领域。实际开发中建议结合Web Audio API实现更复杂的音频处理,但基础TTS功能已能满足80%的常见需求。