Skip to content

Instantly share code, notes, and snippets.

@JT5D
Forked from hecomi/server.js
Last active August 29, 2015 14:25
Show Gist options
  • Save JT5D/d502e9b4fde4bf7b2443 to your computer and use it in GitHub Desktop.
Save JT5D/d502e9b4fde4bf7b2443 to your computer and use it in GitHub Desktop.
SimSimi API と Web Speech API と Unity をつなげるやつ
var http = require('http');
var https = require('https');
var querystring = require('querystring');
var fs = require('fs');
var ws = require('ws').Server;
var wss = [];
var HTTPS_PORT = 23456;
var UNITY_PORT = 12345;
var HTML_PATH = 'index.html';
var SIMSIMI_API_KEY = 'SimSimi に登録して得た API キー';
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
// WebSpeech API を Chrome で走らせるための HTTPS サーバ
var server = https.createServer(options, function(req, res) {
fs.readFile(HTML_PATH, function(err, data) {
if (err) {
res.writeHead(500);
res.end('Internal Server Error');
} else {
res.writeHead(200);
res.end(data.toString());
}
});
}).listen(HTTPS_PORT);
// Unity と WebSocket によるコネクションをはる
var wsUnityServer = new ws({port: UNITY_PORT});
wsUnityServer.on('connection', function(ws) {
console.log('unity connected');
wss.push(ws);
ws.on('close', function(message) {
console.log('unity disconnected');
wss.splice(wss.indexOf(ws), 1);
});
});
// SimSimi API を叩く
var callSimSimiAPI = function(word, callback) {
var query = {
key : SIMSIMI_API_KEY,
lc : 'ja',
ft : 1.0,
text: word
};
http.get({
host: 'sandbox.api.simsimi.com',
path: '/request.p?' + querystring.stringify(query)
}, function(simsimiRes) {
var jsonStr = '';
simsimiRes.on('data', function(chunk) {
jsonStr += chunk;
}).on('end', function() {
var response = JSON.parse(jsonStr).response;
if (response === undefined) {
callback('API 制限を超えているかエラーです。', undefined);
}
if (typeof(callback) === 'function') {
callback(null, response);
}
});
});
};
// WebSpeech API の結果を取ってくるための WebSocket
var wsVoiceRecogServer = new ws({server: server});
wsVoiceRecogServer.on('connection', function(ws) {
ws.on('message', function(word) {
console.log('recognized:', word);
callSimSimiAPI(word, function(err, result) {
if (err) {
console.error(err);
} else {
console.log('reply:', result);
wss.forEach(function(ws) {
ws.send(result);
});
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment