Skip to content

Instantly share code, notes, and snippets.

@possan
Created February 15, 2013 17:30
Show Gist options
  • Save possan/4961928 to your computer and use it in GitHub Desktop.
Save possan/4961928 to your computer and use it in GitHub Desktop.
Simple rest-y osx text-to-speech service returning mp3's
var restify = require('restify');
var crypto = require('crypto');
var spawn = require('child_process').spawn;
var fs = require('fs');
function voiceRespond(req, res, next) {
var voice = req.params.voice;
var text = req.query.text;
var key = voice+'___'+text;
var hash = crypto.createHash('md5').update(key).digest("hex");
var fileprefix = '/tmp/voice_'+hash;
var aiff = fileprefix+'.aiff';
var mp3 = fileprefix+'.mp3';
var applescript = 'say "' + text +'" using "'+voice+'" saving to "'+aiff+'"';
// if file exists, don't transcode, just return mp3
if (fs.existsSync(mp3)) {
// res.send('cached voice.');
fs.readFile(mp3, function (err, data) {
res.setHeader('Content-Type', 'audio/mp3');
res.writeHead(200);
res.end(data);
});
return;
}
// speak
var proc = spawn('osascript', ['-e', applescript]);
proc.on('exit', function (code, signal) {
console.log('child process terminated due to receipt of signal '+signal);
// transcode
var proc2 = spawn('lame', [aiff, mp3]);
proc2.on('exit', function (code, signal) {
console.log('child process terminated due to receipt of signal '+signal);
// res.send('voice ' + voice + ';; text ' + text+';; script '+applescript);
fs.readFile(mp3, function (err, data) {
res.setHeader('Content-Type', 'audio/mp3');
res.writeHead(200);
res.end(data);
});
});
});
}
function indexRespond(req, res, next) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end('try <a href=\"/v/fred/audio.mp3?text=hello%20world\">/v/fred/audio.mp3?text=hello%20world</a>');
}
var server = restify.createServer();
server.use(restify.queryParser());
server.get('/', indexRespond);
server.head('/', indexRespond);
server.get('/v/:voice/audio.mp3', voiceRespond);
server.head('/v/:voice/audio.mp3', voiceRespond);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment