js实现英文发音
实现英文发音的方法
在JavaScript中实现英文发音通常可以通过Web Speech API中的SpeechSynthesis接口完成。该API允许浏览器将文本转换为语音,支持多种语言和声音选项。
使用SpeechSynthesis API
初始化SpeechSynthesis对象并设置需要朗读的文本:
const utterance = new SpeechSynthesisUtterance('Hello, how are you today?');
设置语音参数(如语言、音调、语速等):
utterance.lang = 'en-US'; // 设置为美式英语
utterance.pitch = 1.0; // 音调(0-2)
utterance.rate = 1.0; // 语速(0.1-10)
utterance.volume = 1.0; // 音量(0-1)
调用speechSynthesis.speak()方法朗读文本:
window.speechSynthesis.speak(utterance);
获取可用语音列表
可以通过speechSynthesis.getVoices()获取浏览器支持的语音列表,并筛选出英文语音:
const voices = window.speechSynthesis.getVoices();
const englishVoices = voices.filter(voice => voice.lang.includes('en'));
设置特定语音:

utterance.voice = englishVoices[0]; // 选择第一个英文语音
监听语音事件
可以监听语音开始、结束、错误等事件:
utterance.onstart = () => console.log('Speech started');
utterance.onend = () => console.log('Speech ended');
utterance.onerror = (event) => console.error('Speech error', event);
暂停和恢复语音
暂停当前语音:
window.speechSynthesis.pause();
恢复暂停的语音:

window.speechSynthesis.resume();
取消所有语音:
window.speechSynthesis.cancel();
兼容性注意事项
Web Speech API在现代浏览器中支持良好,但在某些旧版本浏览器中可能不支持。使用前建议检查兼容性:
if ('speechSynthesis' in window) {
// API可用
} else {
console.log('Speech Synthesis API not supported');
}
替代方案
如果浏览器不支持Web Speech API,可以考虑以下替代方案:
- 使用第三方TTS服务(如Google Cloud Text-to-Speech)
- 预录制音频文件并播放
- 使用Electron或React Native等框架的本地TTS功能
示例完整代码
function speak(text) {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'en-US';
// 等待语音列表加载
speechSynthesis.onvoiceschanged = function() {
const voices = speechSynthesis.getVoices();
const englishVoice = voices.find(voice => voice.lang === 'en-US');
if (englishVoice) {
utterance.voice = englishVoice;
}
speechSynthesis.speak(utterance);
};
// 如果语音列表已经加载
if (speechSynthesis.getVoices().length > 0) {
speechSynthesis.onvoiceschanged();
}
} else {
alert('Text-to-speech not supported in your browser');
}
}
// 使用示例
speak('Hello world, this is a text to speech example');
语音控制增强
可以通过按钮控制语音播放:
<button onclick="speak('Hello')">Speak</button>
<button onclick="window.speechSynthesis.pause()">Pause</button>
<button onclick="window.speechSynthesis.resume()">Resume</button>
<button onclick="window.speechSynthesis.cancel()">Stop</button>
