No Description

node-speakable.js 3.2KB

    // Wit.ai API var EventEmitter = require('events').EventEmitter, util = require('util'), spawn = require('child_process').spawn, http = require('follow-redirects').http; https = require('follow-redirects').https; var Speakable = function Speakable(credentials, options) { EventEmitter.call(this); options = options || {} this.recBuffer = []; this.recRunning = false; this.apiResult = {}; this.apiLang = options.lang || "en-US"; this.apiKey = credentials.key this.cmd = (options.sox_path) || 'sox'; this.cmdArgs = [ '-q', '-v', '0.98', '-b','16', '-d','-t','mp3','-', 'rate','8000','channels','1', 'silence','1','0.1',(options.threshold || '0.1')+'%2','1','1.0',(options.threshold || '0.1')+'%2' ]; }; util.inherits(Speakable, EventEmitter); module.exports = Speakable; Speakable.prototype.postVoiceData = function() { var self = this; var options = { hostname: 'api.wit.ai', path: '/speech', maxRedirects: 10, method: 'POST', headers: { "Authorization": "Bearer Q6NTRBF6CVKOGJUQFZGHASQSLKRAX4SX", 'Content-Type': 'audio/mpeg3' } }; var req = https.request(options, function(res) { self.recBuffer = []; res.setEncoding('utf8'); res.on('data', function (chunk) { console.log(chunk); self.apiResult = JSON.parse(chunk); }); if(res.statusCode !== 200) { return self.emit( 'error', 'Non-200 answer from Wit.ai Speech API (' + res.statusCode + ') \n' + JSON.stringify(res.headers) ); } res.on('end', function() { self.parseResult(); }); }); req.on('error', function(e) { self.emit('error', e); }); // write data to request body console.log('Posting voice data...'); for(var i in self.recBuffer) { if(self.recBuffer.hasOwnProperty(i)) { req.write(new Buffer(self.recBuffer[i],'binary')); console.log(new Buffer(self.recBuffer[i],'binary')) } } req.end(); }; Speakable.prototype.recordVoice = function() { var self = this; var rec = spawn(self.cmd, self.cmdArgs, { stdio: 'pipe' }); // Process stdout rec.stdout.on('readable', function() { self.emit('speechReady'); }); rec.stdout.setEncoding('binary'); rec.stdout.on('data', function(data) { if(! self.recRunning) { self.emit('speechStart'); self.recRunning = true; } self.recBuffer.push(data); }); // Process stdin rec.stderr.setEncoding('utf8'); rec.stderr.on('data', function(data) { console.log(data) }); rec.on('close', function(code) { self.recRunning = false; if(code) { self.emit('error', 'sox exited with code ' + code); } self.emit('speechStop'); self.postVoiceData(); }); }; Speakable.prototype.resetVoice = function() { var self = this; self.recBuffer = []; } Speakable.prototype.parseResult = function() { var recognizedWords = [], apiResult = this.apiResult.result; if(apiResult && apiResult.length > 0 && apiResult[0].alternative && apiResult[0].alternative[0]) { recognizedWords = apiResult[0].alternative[0].transcript.split(' '); this.emit('speechResult', recognizedWords); } else { this.emit('speechResult', []); } }