js实现听书
使用 Web Speech API 实现文本朗读
Web Speech API 的 SpeechSynthesis 接口可以直接将文本转换为语音。以下是一个基础实现示例:

// 获取语音合成对象
const synth = window.speechSynthesis;
function speak(text) {
// 创建语音实例
const utterance = new SpeechSynthesisUtterance(text);
// 设置语音参数(可选)
utterance.rate = 1; // 语速 (0.1-10)
utterance.pitch = 1; // 音高 (0-2)
utterance.lang = 'zh-CN'; // 中文普通话
// 开始朗读
synth.speak(utterance);
}
// 调用示例
speak("这是一个JavaScript实现的听书功能演示");
自定义语音参数
可以通过以下方式调整语音效果:

// 获取所有可用语音
const voices = synth.getVoices();
// 设置特定语音(需在voices加载后调用)
utterance.voice = voices.find(v => v.lang === 'zh-CN');
// 事件监听
utterance.onboundary = (e) => {
console.log(`当前朗读到: ${e.charIndex}位置`);
};
实现播放控制
添加暂停、继续和停止功能:
let currentUtterance = null;
function pauseSpeaking() {
synth.pause();
}
function resumeSpeaking() {
synth.resume();
}
function stopSpeaking() {
synth.cancel();
}
// 修改speak函数保存当前实例
function speak(text) {
stopSpeaking();
currentUtterance = new SpeechSynthesisUtterance(text);
synth.speak(currentUtterance);
}
处理长文本分页
对于长文本内容,建议分页朗读:
const bookContent = "长文本内容...";
const chunks = bookContent.match(/[\s\S]{1,500}/g) || []; // 每500字符分块
let currentChunk = 0;
function readNextChunk() {
if (currentChunk < chunks.length) {
speak(chunks[currentChunk]);
currentUtterance.onend = () => {
currentChunk++;
readNextChunk();
};
}
}
// 开始朗读整本书
readNextChunk();
浏览器兼容性注意事项
- Web Speech API 在 Chrome、Edge、Safari 中支持较好
- 在iOS设备上需要用户交互(如点击事件)才能触发语音
- 部分浏览器可能需要HTTPS环境
// 兼容性检查
if (!('speechSynthesis' in window)) {
alert('您的浏览器不支持语音合成功能');
}
增强功能建议
- 添加进度条显示朗读进度
- 实现书签功能保存阅读位置
- 添加语速调节滑块控件
- 支持多语言切换
- 结合LocalStorage保存用户设置
完整实现可参考MDN文档的SpeechSynthesis相关示例。






