JavaScript可通过Web Speech API的SpeechSynthesis接口实现浏览器端语音合成,需检测support、处理音色加载延迟、设置参数并调用speak,注意移动端需用户手势触发且存在兼容性限制。
JavaScript 可以通过浏览器内置的 Web Speech API 中的 SpeechSynthesis 接口实现语音合成,无需第三方库或后端支持,兼容 Chrome、Edge、Safari(部分支持)、Firefox(需手动启用)等主流桌面浏览器。
不是所有环境都默认启用该功能,尤其移动端限制较多。使用前应先检测:
```js
if ('speechSynthesis' in window) {
console.log('支持语音合成');
} else {
console.log('不支持');
}
```
核心流程分四步:获取实例 → 选择音色 → 创建语音内容 → 播放
window.speechSynthesis 获取合成器实例getVoices() 获取可用音色列表(注意:首次调用可能为空,需监听 voiceschanged 事件)SpeechSynthesisUtterance(text) 创建语音任务对象rate)、音高(pitch)、音量(volume)等属性,再调用 speechSynthesis.speak(utterance)
Chrome 等浏览器中,speechSynthesis.getVoices() 初次调用常返回空数组。正确做法是监听事件:
```js
function speak(text) {
const synth = window.speechSynthesis;
let voices = synth.getVoices();
if (voices.length === 0) {
synth.onvoiceschanged = () => {
voices = synth.getVoices();
pl
ayWithVoice(text, voices);
};
} else {
playWithVoice(text, voices);
}
}
function playWithVoice(text, voices) {
const utterance = new SpeechSynthesisUtterance(text);
// 例如选中文音色(按语言过滤)
const cnVoice = voices.find(v => v.lang.includes('zh')) || voices[0];
utterance.voice = cnVoice;
utterance.rate = 1.0;
utterance.pitch = 1.2;
window.speechSynthesis.speak(utterance);
}
```
speechSynthesis.pause()、.resume()、.cancel()
onstart、onend、onerror 等事件speak)