js实现英文发音
使用Web Speech API实现英文发音
Web Speech API的SpeechSynthesis接口可直接在浏览器中实现文本转语音功能,无需第三方库。以下为基本实现方法:
function speakEnglish(text) {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'en-US'; // 设置英文发音
speechSynthesis.speak(utterance);
}
调整发音参数
可通过修改SpeechSynthesisUtterance对象属性控制发音效果:
const utterance = new SpeechSynthesisUtterance("Hello World");
utterance.rate = 1.0; // 语速 (0.1-10)
utterance.pitch = 1.0; // 音高 (0-2)
utterance.volume = 1.0;// 音量 (0-1)
浏览器兼容性处理
检测浏览器支持情况并提供备用方案:
if ('speechSynthesis' in window) {
// 支持Web Speech API
} else {
console.error("该浏览器不支持语音合成功能");
// 可在此处回退到第三方库方案
}
使用第三方库(如responsive-voice)
如需更多语音选项或更好兼容性,可引入第三方库:
<script src="https://code.responsivevoice.org/responsivevoice.js"></script>
<script>
responsiveVoice.speak("Hello world", "US English Female");
</script>
发音事件监听
监听语音合成事件实现更精细控制:
utterance.onstart = () => console.log('开始发音');
utterance.onend = () => console.log('发音结束');
utterance.onerror = (e) => console.error('发音错误', e);
获取可用语音列表
动态获取浏览器支持的语音引擎:

function listVoices() {
return speechSynthesis.getVoices().filter(v => v.lang.startsWith('en'));
}
// 注意需要等待voiceschanged事件
speechSynthesis.onvoiceschanged = listVoices;





