speech.js 1.38 KB
/** html5 Web Speech 相关 */

var h5Speech = (function(){
	
	//发音速度 1 ~ 10;
	var rate;
	//队列播放模式 1:覆盖式  -1:完整顺序播报
	var queueModel;
	var synth = window.speechSynthesis;
	
	//读取配置信息
	readCofig();
	var speechInstance = {
		speak: function(t){
			if(queueModel == 1)
				synth.cancel();
			
			//延迟一会,防止 synth.cancel 将当前项也从队列移除
			setTimeout(function(){
				var msg = new SpeechSynthesisUtterance(t);
				msg.rate = rate;
				synth.speak(msg);
			}, 100);
		},
		speakTest: function(t, rate){
			var msg = new SpeechSynthesisUtterance(t);
			msg.rate = rate;
			synth.speak(msg);
		},
		getCofig: function(){
			return {rate: rate, queueModel: queueModel};
		},
		setCofig: function(r, q){
			rate = r;
			queueModel = q;
			writeCofig(rate, queueModel);
			
			return 1;
		}
	};
	return speechInstance;
	
	function readCofig(){
		//读取配置信息
		var ttsCofig = storage.getItem('tts_cofig');
		if(ttsCofig){
			ttsCofig = JSON.parse(ttsCofig);
			rate = ttsCofig.rate;
			queueModel = ttsCofig.queueModel;
		}
		else{
			//写入默认配置
			rate = 1.2;
			queueModel = 1;
			writeCofig(rate, queueModel);
		}
	}
	
	function writeCofig(rate, queueModel){
		storage.setItem('tts_cofig', JSON.stringify({rate: rate, queueModel: queueModel}));
	}
})();