81041
2018-10-29 f4b4ace227b35ef357db0a8545629588419d344a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 设置语音播报对象
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();