// 设置语音播报对象
|
var Voice = function() {
|
this.speak = window.speechSynthesis;
|
this.voice = '';
|
this.zh_CN = false;
|
this._setLang(); // 获取并检测是否有中文的环境
|
};
|
|
// 播报语音 (调用发声的方法时请使用延时发声)
|
Voice.prototype.play = function(txt) {
|
if(!this.zh_CN) {
|
console.info('你的电脑不支持中文播报!');
|
}
|
console.info(this.zh_CN);
|
this.cancel();
|
var to_speak = new SpeechSynthesisUtterance(txt);
|
to_speak.voice = this.voice; // 设定中文播报
|
|
this.speak.speak(to_speak);
|
|
};
|
|
// 退出当前播报
|
Voice.prototype.cancel = function() {
|
this.speak.cancel();
|
};
|
|
// 检查当前语言环境
|
Voice.prototype._setLang = function() {
|
var _this = this;
|
setTimeout(function(){
|
var voices = _this.speak.getVoices();
|
for(var i=0; i<voices.length; i++) {
|
var _voices = voices[0];
|
//console.info(_voices);
|
if(_voices.lang === 'zh-CN') {
|
_this.zh_CN = true;
|
_this.voice = _voices;
|
}
|
}
|
}, 0);
|
};
|
|
var voice = new Voice();
|