js实现语音播报
实现语音播报的基本方法
使用Web Speech API中的SpeechSynthesis接口可以实现文本转语音(TTS)功能。该API允许浏览器直接朗读文本内容,无需依赖第三方服务。
const utterance = new SpeechSynthesisUtterance('你好,这是一段测试语音');
window.speechSynthesis.speak(utterance);
自定义语音参数
可以调整语音的音调、语速、音量等参数,以及选择不同的语音引擎。
const utterance = new SpeechSynthesisUtterance();
utterance.text = '自定义语音参数测试';
utterance.rate = 1.2; // 语速 (0.1-10)
utterance.pitch = 1.5; // 音调 (0-2)
utterance.volume = 0.8; // 音量 (0-1)
// 获取可用语音列表并选择
const voices = window.speechSynthesis.getVoices();
utterance.voice = voices.find(voice => voice.lang === 'zh-CN');
window.speechSynthesis.speak(utterance);
处理语音列表加载
语音列表可能需要时间加载,需要监听voiceschanged事件。
window.speechSynthesis.onvoiceschanged = function() {
const voices = window.speechSynthesis.getVoices();
console.log('可用语音:', voices);
};
控制播放状态
可以暂停、恢复或取消当前的语音播报。
// 暂停
window.speechSynthesis.pause();
// 恢复
window.speechSynthesis.resume();
// 取消
window.speechSynthesis.cancel();
事件监听
可以为语音播报添加各种事件监听,如开始、结束、错误等。
utterance.onstart = function(event) {
console.log('语音开始播放');
};
utterance.onend = function(event) {
console.log('语音播放结束');
};
utterance.onerror = function(event) {
console.error('播放出错:', event.error);
};
浏览器兼容性处理
检查浏览器是否支持SpeechSynthesis API,并提供备用方案。
if ('speechSynthesis' in window) {
// 支持语音合成
} else {
console.warn('当前浏览器不支持语音合成API');
// 可以降级使用第三方TTS服务或提示用户
}
实际应用示例
结合用户交互实现点击按钮播放语音的功能。

<button id="speakBtn">播放语音</button>
<textarea id="textInput" placeholder="输入要朗读的文本"></textarea>
<script>
document.getElementById('speakBtn').addEventListener('click', function() {
const text = document.getElementById('textInput').value;
if (!text) return;
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);
});
</script>
注意事项
语音合成API在不同浏览器和设备上表现可能不一致,特别是在移动设备上可能会有额外限制。某些浏览器可能需要用户交互(如点击事件)后才能触发语音播放。中文语音支持取决于操作系统和浏览器,Windows系统通常自带中文语音引擎,而MacOS可能需要额外安装。






