hdw
2018-11-02 89cc717e3ccd49d49539b25d7a8554126504b51f
gx_tieta/WebRoot/js/VoiceUtil.js
@@ -1,28 +1,67 @@
// 设置语音播报对象
var Voice = function() {
   this.speak = window.speechSynthesis;
   this.tospeak = new SpeechSynthesisUtterance('');
   this.voice = '';
   this.zh_CN = false;
   this._setLang();   // 获取并检测是否有中文的环境
   this.rate = 1.5;
   this._setLang();         // 获取并检测是否有中文的环境
   this.timeInterval = 27;      //循环间隔(秒)
   this.speak_enable = true;         //ture:开启语音播报         false:停止语音播报
};
// 播报语音      (调用发声的方法时请使用延时发声)
Voice.prototype.play = function(txt) {
Voice.prototype.play = function(txt,callback) {
   if(!this.zh_CN) {
      console.info('你的电脑不支持中文播报!');      
   }
   console.info(this.zh_CN);
   _timeInterval = this.timeInterval;
   //console.info(this.speak_enable);
   if(!this.speak_enable){                           //识别是否开启声音播报
      if(callback && typeof callback == 'function'){
         setTimeout(function(){
            callback();
         }, Math.abs(_timeInterval)*1000);
      }
      return;
   }
   this.cancel();
   var to_speak = new SpeechSynthesisUtterance(txt);
   to_speak.voice = this.voice;   // 设定中文播报
   this.speak.speak(to_speak);
   this.tospeak.text = txt;
   this.tospeak.voice = this.voice;   // 设定中文播报
   this.tospeak.rate = this.rate;
   //console.info(to_speak);
   var starttime = new Date();
   this.speak.speak(this.tospeak);
   //console.info(this.tospeak);
   this.tospeak.onend = function(event) {
      //console.info("播放结束");
      if(callback && typeof callback == 'function'){
         var endtime = new Date();
         var timelong = (endtime.getTime()-starttime.getTime())/1000;
         //console.info(parseInt(_timeInterval)+"==="+parseInt(timelong));
         if(timelong > this.timeInterval){
            callback();
         }else{
            setTimeout(function(){
               callback();
            }, Math.abs(_timeInterval-timelong)*1000);
         }
      }
   };
   
};
// 退出当前播报
Voice.prototype.cancel = function() {
   this.speak.cancel();
};
//停止语音播报
Voice.prototype.stopSpeak = function() {
   this.speak.cancel();
   this.speak_enable = false;
};
// 检查当前语言环境
@@ -41,4 +80,7 @@
   }, 0);
};
var voice = new Voice();
voice.cancel();