Skip to content

Instantly share code, notes, and snippets.

@pete-rai
Created February 18, 2018 22:36
Show Gist options
  • Save pete-rai/dc894c13f11de6e9634eb3379fb39c3b to your computer and use it in GitHub Desktop.
Save pete-rai/dc894c13f11de6e9634eb3379fb39c3b to your computer and use it in GitHub Desktop.
A lean wrapper around Amazon Polly (which doesn't need the full AWS-SDK) making text-to-speech in nodejs super simple.
'use strict'
/*
first install the following node modules:
npm install aws4
npm install https
npm install querystring
npm install speaker
npm install lame
npm install fs
npm install ini
if after running the sample, you get an error 'Illegal instruction: 4'
then also do the following step, AFTER those above:
npm install speaker --mpg123-backend=openal
also sure that you have an accesible file which contains your aws
credentials in this form:
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
when all set-up, run the sample like this:
node polly.js
*/
// --- dependencies
const aws4 = require ('aws4');
const https = require ('https');
const query = require ('querystring');
const speaker = require ('speaker');
const lame = require ('lame');
const fs = require ('fs');
const ini = require ('ini');
// --- the polly class
function Polly (credentials, region)
{
var config = ini.parse (fs.readFileSync (credentials, 'utf-8'));
this._key = { accessKeyId: config.default.aws_access_key_id, secretAccessKey: config.default.aws_secret_access_key };
this._say = { OutputFormat: 'mp3', VoiceId: 'Amy' };
this._req = { service: 'polly', region: region, signQuery: true };
this._spk = { channels: 1, bitDepth: 16, sampleRate: 22050 };
this.voice = function (voice) // see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
{
this._say.VoiceId = voice;
}
this.say = function (utterance, callback)
{
this._say.Text = utterance;
this._req.path = '/v1/speech?' + query.stringify (this._say);
https.request (aws4.sign (this._req, this._key), function (audio)
{
audio.pipe (lame.Decoder ())
.pipe (new speaker (this._spk))
.on ('finish', function ()
{
if (callback) callback ();
});
})
.end();
}
}
// --- example usage
var polly = new Polly ('./credentials', 'us-west-2');
console.log ();
console.log ('Ulysses by Sir Alfred Lord Tennyson');
console.log ();
polly.say ('We are not now that strength, which in old days moved Earth and heaven', function ()
{
polly.voice ('Brian');
polly.say ('That which we are we are. One equal temper of heroic hearts', function ()
{
polly.voice ('Emma');
polly.say ('Made weak by time and fate, but strong in will', function ()
{
polly.voice ('Raveena');
polly.say ('To strive, to seek, to find, and not to yield.'); // no callback here, as its optional
});
});
});
@pete-rai
Copy link
Author

pete-rai commented Feb 27, 2020 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment