心理咨询网站后台,江西省赣州市定南县,城乡建设管理局网站,免费企业网站建设哪种实现语音播报要有两个原生API
分别是【window.speechSynthesis】【SpeechSynthesisUtterance】
项目代码
// 执行函数
initVoice({text: 项目介绍,vol: 1,rate: 1
})// 函数
export function initVoice(config) {window.speechSynthesis.cancel();//播报前建议调用取消的函数…实现语音播报要有两个原生API
分别是【window.speechSynthesis】【SpeechSynthesisUtterance】
项目代码
// 执行函数
initVoice({text: 项目介绍,vol: 1,rate: 1
})// 函数
export function initVoice(config) {window.speechSynthesis.cancel();//播报前建议调用取消的函数如有正在播报的话音播报会任务被塞进入队列只有等上一个语音结束才会执行下一个语音//获取语音包let listArr window.speechSynthesis.getVoices();listArr listArr.filter(item item.lang.indexOf(zh-) -1);if (listArr.length 0) {console.error(没有可用的中文语音!);}//实例化播报内容let instance new SpeechSynthesisUtterance();instance.text config.text || 轻轻敲醒沉睡的心灵慢慢张开你的眼睛看看忙碌的世界是否依然孤独的转个不停; // 文字内容instance.lang config.lang || zh-CN; // 使用的语言:中文instance.volume config.vol || 1; // 声音音量1instance.rate config.rate || 1; // 语速1instance.pitch 1; // 音高1window.speechSynthesis.speak(instance); // 播放instance.addEventListener(end, () {});// 监听播报完成状态播完可以做些其它处理
}将函数拷贝到项目中执行函数即可实现。
下面列出一些常用的执行方法
//获取可用的语音包如果返回数组是空则没有可用的语音包。不同浏览器的语音包数量是不一样的。
window.speechSynthesis.getVoices();//instance是SpeechSynthesisUtterance的实例绑定了语音包。将话语添加到话语队列中当任何其他话语在它被说出之前排队时它将被说出。
window.speechSynthesis.speak(instance); // 取消语音
window.speechSynthesis.cancel();//暂停语音
// window.speechSynthesis.pause();//恢复语音window.SpeechSynthesis.resume(); 注意在某些浏览器必须先提前调用【window.speechSynthesis.getVoices();】方法再异步执行上面【完整语音播报】再能播报语音。
原因是第一次【window.speechSynthesis.getVoices();】获取的数据是空数组。
第二次异步调用【window.speechSynthesis.getVoices();】才返回非空数组。