js实现听书
使用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};
}
完整实现示例
整合上述功能的完整组件实现。

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设备上存在自动暂停的限制,需要特定交互才能继续播放
- 语音质量和可用性取决于用户操作系统和浏览器
- 长时间文本建议分段朗读以避免内存问题






