js实现tts
使用Web Speech API实现TTS
Web Speech API是浏览器原生支持的语音合成接口,无需额外库即可实现文本转语音功能。
// 创建语音合成实例
const synth = window.speechSynthesis;
// 创建语音内容
const utterance = new SpeechSynthesisUtterance('你好,这是测试语音');
// 设置语音参数
utterance.rate = 1; // 语速 (0.1-10)
utterance.pitch = 1; // 音高 (0-2)
utterance.volume = 1; // 音量 (0-1)
// 获取可用语音列表
const voices = synth.getVoices();
// 设置特定语音(需等待voiceschanged事件)
utterance.voice = voices.find(voice => voice.lang === 'zh-CN');
// 执行语音合成
synth.speak(utterance);
使用第三方库responsive-voice
responsive-voice.js提供更简单的API和跨浏览器支持。

<script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script>
responsiveVoice.speak("这是测试文本", "Chinese Female", {
pitch: 1,
rate: 1,
volume: 1
});
</script>
实现语音队列系统
对于需要连续播放多个语音的场景,可以建立队列系统。

class TTSQueue {
constructor() {
this.queue = [];
this.synth = window.speechSynthesis;
this.isSpeaking = false;
}
add(text, lang = 'zh-CN') {
this.queue.push({text, lang});
if (!this.isSpeaking) this.processQueue();
}
processQueue() {
if (this.queue.length === 0) {
this.isSpeaking = false;
return;
}
this.isSpeaking = true;
const {text, lang} = this.queue.shift();
const utterance = new SpeechSynthesisUtterance(text);
utterance.voice = this.synth.getVoices()
.find(voice => voice.lang === lang);
utterance.onend = () => this.processQueue();
this.synth.speak(utterance);
}
}
// 使用示例
const tts = new TTSQueue();
tts.add("第一条消息");
tts.add("第二条消息", "en-US");
浏览器兼容性处理
不同浏览器对语音合成的支持存在差异,需要进行兼容性检测。
function checkTTSsupport() {
if (!('speechSynthesis' in window)) {
console.error('该浏览器不支持语音合成API');
return false;
}
// 检测中文语音支持
const voices = speechSynthesis.getVoices();
const hasChinese = voices.some(v => v.lang.includes('zh'));
if (!hasChinese) {
console.warn('未找到中文语音引擎');
}
return true;
}
// 建议在voiceschanged事件后检测
speechSynthesis.onvoiceschanged = checkTTSsupport;
语音合成事件监听
通过事件监听可以实现更精细的控制。
const utterance = new SpeechSynthesisUtterance('测试事件');
utterance.onstart = (event) => {
console.log('语音开始播放');
};
utterance.onend = (event) => {
console.log('语音播放结束');
};
utterance.onerror = (event) => {
console.error('发生错误:', event.error);
};
utterance.onpause = (event) => {
console.log('语音暂停');
};
utterance.onresume = (event) => {
console.log('语音恢复');
};
speechSynthesis.speak(utterance);
注意事项
- 某些浏览器需要用户交互(如点击事件)后才能触发语音播放
- 移动设备可能有额外的限制或不同的行为
- 语音质量取决于用户设备安装的语音引擎
- 长时间文本可能需要分段处理以避免性能问题






