Created
April 24, 2018 14:14
-
-
Save kopiro/883875248cfa40af4f83b744ea9711a1 to your computer and use it in GitHub Desktop.
Convert text to mp3 using AWS Polly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const aws = require('aws-sdk'); | |
aws.config.loadFromPath('aws.json'); | |
const locale = 'it-IT'; | |
const fs = require('fs'); | |
const pollyClient = new aws.Polly({ | |
signatureVersion: 'v4', | |
region: 'eu-west-1' | |
}); | |
function getVoice() { | |
return new Promise((resolve, reject) => { | |
pollyClient.describeVoices({ | |
LanguageCode: locale | |
}, async(err, data) => { | |
if (err != null) { | |
if (err.code !== 'ValidationException') { | |
console.error(TAG, err); | |
return reject(err); | |
} | |
} | |
voice = data.Voices.find((v) => { | |
return v.Gender == "Female"; | |
}); | |
return resolve(voice); | |
}); | |
}); | |
} | |
function getAudioFile(id, text) { | |
return new Promise(async(resolve, reject) => { | |
console.debug('request', { text }); | |
const ssml = /<speak>/.test(text); | |
let voice = await getVoice(); | |
pollyClient.synthesizeSpeech({ | |
VoiceId: voice.Id, | |
Text: text, | |
TextType: ssml ? 'ssml' : 'text', | |
OutputFormat: 'mp3', | |
}, (err, data) => { | |
if (err) { | |
console.error(err); | |
return reject(err); | |
} | |
let file = __dirname + '/' + id + '.mp3'; | |
fs.writeFile(file, data.AudioStream, function(err) { | |
if (err) { | |
throw err; | |
} | |
console.log('File saved to ' + file); | |
}); | |
}); | |
}); | |
}; | |
getAudioFile(process.argv[1], process.argv[2]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment