SpeechSynthesisUtterance是HTML5中新增的API,用于将指定文字合成为对应的语音.也包含一些配置项,指定如何去阅读(语言,音量,音调)等,不支持IE浏览器。
- api文档 https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance/onend
SpeechSynthesisUtterance案例
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><input type="text" id="textMsg" value="有新的订单,请及时处理"><button onclick="speak()">播放</button><button onclick="pause()">暂停</button><button onclick="resume()">继续播放</button><button onclick="cancel()">取消播放</button><script>var synth = window.speechSynthesis //来创建语音,var speech = new SpeechSynthesisUtterance();//来创建文本实例// 播放function speak() {//speech.pitch = 1 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)// speech.rate = 5 // 获取并设置说话的速度(值越大语速越快,越小语速越慢 0.1-10)// speech.volume = 100 // 获取并设置说话的音量// speech.lang = 'zh-CN' //语言//返回当前设备所有可用声音的 SpeechSynthesisVoice (en-US)列表。//var voices = synth.getVoices();//console.log(voices);//speech.voice = voices[0];speech.text = textMsg.value; // 获取并设置说话时的文本synth.cancel();//先关闭所有队列在播放 防止点击几次播放几次语音synth.speak(speech);//将对应的实例添加到语音队列中}// 暂停function pause() {synth.pause()}// 继续播放function resume() {synth.resume()}// 取消播放function cancel() {synth.cancel()}//当口语到达单词或句子边界时触发boundary。 也可通过onboundary获得//当话语说完时触发end ,也可通过onend获得speech.addEventListener('end',function(){console.log('语音播报结束')});speech.onend = function(){console.log('语音播报结束')}</script></body></html>
