tts.min.js 7.3 KB
/*
 author:cyhu(viskey.hu@gmail.com) 2015.4.14

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in
 the documentation and/or other materials provided with the distribution.

 3. The names of the authors may not be used to endorse or promote products
 derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
 INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var brower_info = {
	"sys": null,
	"type": null,
	"link": null
};
/* */
var print_log = true;

var websocket_url = 'ws://h5.xf-yun.com/tts.do';

var reconnection = false;
var reconnection_delay = 999999;
var force_new_connection = true;
var buffer_length = 0;
var tts_params_obj = null;
this.node = null;
var tts_session_id = null;
var tts_text_ready = null;
var func_on_tts_process = null;
var func_on_tts_result = null;
var browser_id = new Fingerprint().get();
var is_re_request = false;
var request_synid = null;

var ua = navigator.userAgent.toLowerCase();
if (((/msie/.test(ua) && !/opera/.test(ua)) || ((/msie/.test(ua) || /trident/.test(ua)) && !/opera/.test(ua))))
	brower_info.type = 'ie';
else if (ua.match(/firefox\/([\d.]+)/)) {
	brower_info.type = 'firefox';
} else if (ua.match(/chrome\/([\d.]+)/))
	brower_info.type = 'chrome';
else if (ua.match(/opera.([\d.]+)/))
	brower_info.type = 'opera';
else if (ua.match(/version\/([\d.]+).*safari/))
	brower_info.type = 'safari';
else
	brower_info.type = 'other';

if (!!ua.match(/AppleWebKit.*Mobile.*/) || !!ua.match(/AppleWebKit/))
	brower_info.sys = 'mobile';
else if (!!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/))
	brower_info.sys = 'ios';
else if (ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1)
	brower_info.sys = 'android';
else if (ua.indexOf('iPhone') > -1 || ua.indexOf('Mac') > -1)
	brower_info.sys = 'iPhone';
else if (ua.indexOf('iPad') > -1)
	brower_info.sys = 'iPad';
else if (navigator.userAgent.indexOf('MicroMessenger') > -1)
	brower_info.sys = 'Weixin';
else
	brower_info.sys = 'other';

//if(brower_info.type == 'ie' || ((brower_info.type == 'chrome' || brower_info.type == 'opera') &&  brower_info.sys != 'other'))
//{
brower_info.link = 'mp3';
//}else if(brower_info.sys == 'Weixin'){
//brower_info.link = 'mp3';
//}

function register_connection_listener() {
	// console.log("connected to server ...");
	window.socket.onopen = function() {
		var json = {
			"ver": "1.0",
			"sub": "tts",
			"cmd": "ssb",
			"synid": tts_params_obj.synid,
			"msg": "request",
			"appid": tts_params_obj.appid,
			"appkey": tts_params_obj.appkey,
			"data": {
				"params": tts_params_obj.params,
				"text": tts_text_ready
			}
		};
		var resultJson = JSON.stringify(json);
		if (resultJson) {
			window.socket.send(JSON.stringify(json));
		}
	}

	window.socket.onclose = function(e) {
		// console.log("client disconnect ...");
	}

	window.socket.onmessage = function(obj) {

		var json = strToJson(obj.data);
		var cmd = json.cmd;
		var data = json.data;

		is_re_request = true;
		ttsGetAudioStream(data);
	}
}

function LOGCAT(str) {
	// if (print_log) console.log('[' + getCurrentTime() + ']  ' + str);
}

function getCurrentTime() {
	var now = new Date();
	var year = now.getFullYear();
	var month = now.getMonth() + 1;
	var day = now.getDate();
	var hh = now.getHours();
	var mm = now.getMinutes();

	var clock = year + "-";
	if (month < 10)
		clock += "0";
	clock += month + "-";
	if (day < 10)
		clock += "0";
	clock += day + " ";
	if (hh < 10)
		clock += "0";
	clock += hh + ":";
	if (mm < 10)
		clock += '0';
	clock += mm;
	return (clock);
}

function sendRequestMessage() {
	// console.log("connected to server ...");
	var json = {
		"ver": "1.0",
		"sub": "tts",
		"cmd": "ssb",
		"synid": tts_params_obj.synid,
		"msg": "request",
		"appid": tts_params_obj.appid,
		"appkey": tts_params_obj.appkey,
		"data": {
			"params": tts_params_obj.params,
			"text": tts_text_ready
		}
	};
	var reseltJson = JSON.stringify(json);
	if (reseltJson) {
		window.socket.send(JSON.stringify(json));
	}
};

function initTtsParams(cfg) {
	if (cfg.reconnection != undefined && cfg.reconnection != null) reconnection = cfg.reconnection;
	if (cfg.reconnection_delay != undefined && cfg.reconnection_delay != null) reconnection_delay = cfg.reconnectionDelay;
}

function IFlyTtsSession(cfg) {
	initTtsParams(cfg);

	/*
	 * start a speech synthesize session, schedule: start->send text -> return audio url
	 * ->on end -> next session
	 * @params         parameters for synthesize
	 * @content        content for synthesize
	 * @funcOnResult   on volume listener
	 * @funcOnProcess  on process
	 */
	this.start = function(params, content, funcOnResult, funcOnProcess) {
		iflytek_tts_start(params, content, funcOnResult, funcOnProcess);
	}

	/*
	 * stop synthsize session
	 */
	this.stop = function() {

	}

	/*
	 * cancel synthsize session
	 */
	this.cancel = function() {
		iflytek_tts_cancel();
	}
}

function iflytek_tts_start(params, content, funcOnResult, funcOnProcess) {
	if (arguments.length < 3) {
		LOGCAT("INPUT PARAMETERS ERROR");
		return -1;
	}

	if (funcOnProcess != undefined) func_on_tts_process = funcOnProcess;
	func_on_tts_result = funcOnResult;
	tts_params_obj = params;
	tts_text_ready = content;

	if (window.socket == null || window.socket == undefined || window.socket.readyState != 1) {
		// console.log(websocket_url);
		window.socket = new WebSocket(websocket_url);
	}

	register_connection_listener();

	if (is_re_request) {
		sendRequestMessage();
	};
}

function iflytek_tts_cancel() {
	is_re_request = true;
	LOGCAT("----------tts cancel----------");
}

/*
 * request session end
 */
function ttsSessionEnd(wait_time) {
	is_re_request = true;
	LOGCAT("----------session end----------");
}

function strToJson(str) {
	var json = eval('(' + str + ')');
	return json;
}

function ttsGetAudioStream(data) {
	if (data.audioKey !== null && data.audioKey !== "") {
		func_on_tts_result(0, {
			"audio_url": data.audioKey,
			"duration": ""
		});
		//console.log("data.audioKey is null", data.audioKey);
	} else {
		//console.log("data.audioKey is null");
	}
	ttsSessionEnd(0);
}