当前位置:首页 > JavaScript

js实现听书

2026-04-05 08:58:36JavaScript

使用Web Speech API实现文本朗读

Web Speech API是浏览器原生支持的语音合成接口,无需额外插件即可实现文本转语音功能。

// 创建语音合成实例
const synth = window.speechSynthesis;

// 朗读文本函数
function speak(text) {
  if (synth.speaking) {
    synth.cancel();
  }

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = 'zh-CN'; // 设置中文语音
  utterance.rate = 1; // 语速 (0.1-10)
  utterance.pitch = 1; // 音高 (0-2)

  synth.speak(utterance);
}

// 调用示例
speak("这是一段测试朗读的文本内容");

添加语音控制功能

扩展基础朗读功能,增加播放控制选项。

// 暂停朗读
function pauseSpeak() {
  if (synth.speaking) {
    synth.pause();
  }
}

// 恢复朗读
function resumeSpeak() {
  if (synth.paused) {
    synth.resume();
  }
}

// 停止朗读
function stopSpeak() {
  synth.cancel();
}

获取可用语音列表

不同浏览器支持的语音引擎不同,可列出可用语音供用户选择。

function getVoices() {
  return new Promise(resolve => {
    const voices = synth.getVoices();
    if (voices.length) {
      resolve(voices);
    } else {
      synth.onvoiceschanged = () => {
        resolve(synth.getVoices());
      };
    }
  });
}

// 使用示例
getVoices().then(voices => {
  console.log(voices.filter(v => v.lang.includes('zh')));
});

实现进度监听

通过事件监听实现朗读进度跟踪。

function speakWithProgress(text, callback) {
  const utterance = new SpeechSynthesisUtterance(text);

  utterance.onboundary = event => {
    if (event.name === 'word') {
      const progress = Math.floor(
        (event.charIndex / text.length) * 100
      );
      callback({progress, word: text.substr(event.charIndex, 10)});
    }
  };

  utterance.onend = () => callback({progress: 100});
  synth.speak(utterance);
}

兼容性处理

针对不支持Web Speech API的浏览器提供备用方案。

function checkCompatibility() {
  if (!('speechSynthesis' in window)) {
    return {
      supported: false,
      message: '当前浏览器不支持语音合成API'
    };
  }
  return {supported: true};
}

完整实现示例

整合上述功能的完整组件实现。

js实现听书

class TextToSpeech {
  constructor() {
    this.synth = window.speechSynthesis;
    this.utterance = null;
  }

  async speak(text, options = {}) {
    this.stop();

    this.utterance = new SpeechSynthesisUtterance(text);
    this.utterance.lang = options.lang || 'zh-CN';
    this.utterance.rate = options.rate || 1;
    this.utterance.pitch = options.pitch || 1;

    if (options.onProgress) {
      this.utterance.onboundary = event => {
        if (event.name === 'word') {
          const progress = Math.floor(
            (event.charIndex / text.length) * 100
          );
          options.onProgress(progress);
        }
      };
    }

    if (options.onEnd) {
      this.utterance.onend = options.onEnd;
    }

    this.synth.speak(this.utterance);
  }

  pause() {
    if (this.synth.speaking) {
      this.synth.pause();
    }
  }

  resume() {
    if (this.synth.paused) {
      this.synth.resume();
    }
  }

  stop() {
    this.synth.cancel();
  }

  static async getVoices() {
    return new Promise(resolve => {
      const voices = window.speechSynthesis.getVoices();
      if (voices.length) {
        resolve(voices);
      } else {
        window.speechSynthesis.onvoiceschanged = () => {
          resolve(window.speechSynthesis.getVoices());
        };
      }
    });
  }
}

注意事项

  • 在Chrome等浏览器中,语音合成API需要用户与页面交互后才能激活
  • iOS设备上存在自动暂停的限制,需要特定交互才能继续播放
  • 语音质量和可用性取决于用户操作系统和浏览器
  • 长时间文本建议分段朗读以避免内存问题

标签: js
分享给朋友:

相关文章

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…