Skip to content

Instantly share code, notes, and snippets.

@Feawel
Last active June 2, 2017 03:13
Show Gist options
  • Save Feawel/0d0bc33d6c32d5c02c6cf0ee2fb11cd6 to your computer and use it in GitHub Desktop.
Save Feawel/0d0bc33d6c32d5c02c6cf0ee2fb11cd6 to your computer and use it in GitHub Desktop.
AWS Polly use example using nodejs async / await
/**
* Use as proxy between front and AWS Polly API
* Everything come in querystring
* voiceId : see Polly API for the list http://docs.aws.amazon.com/fr_fr/polly/latest/dg/API_Voice.html#API_Voice_Contents
* type :
* - file (default) : generate mp3 file on public bucket
* - stream : stream response
*/
export const textToSpeech = async (req, res) => {
const { voiceId = 'Kimberly', text = '', filename = 'speech.mp3', type = 'file' } = req.query
try {
const audio = await generatePollyAudio(text, voiceId)
if(type === 'file') {
const data = await writeAudioStreamToS3(audio.AudioStream, filename)
res.send(data)
}
else if (type === 'stream') {
res.send(audio.AudioStream)
}
else throw { errorCode: 400, error: 'Wrong type for output provided.' }
}
catch (e) {
if(e.errorCode && e.error) res.status(e.errorCode).send(e.error)
else res.status(500).send(e)
}
}
// Generate audio from Polly and check if output is a Buffer
const generatePollyAudio = (text, voiceId) => {
const params = {
Text: text,
OutputFormat: 'mp3',
VoiceId: voiceId
}
return polly.synthesizeSpeech(params).promise().then( audio => {
if (audio.AudioStream instanceof Buffer) return audio
else throw 'AudioStream is not a Buffer.'
})
}
const writeAudioStreamToS3 = ( audioStream, filename ) =>
putObject(aws_publicBucket, filename, audioStream,'audio/mp3').then( res => {
if(!res.ETag) throw res
else return {
msg: 'File successfully generated.',
ETag: res.ETag,
url: `https://s3-eu-west-1.amazonaws.com/${aws_publicBucket}/${filename}`
}
})
const putObject = (bucket, key, body, ContentType) =>
s3.putObject({
Bucket: bucket,
Key: key,
Body: body,
ContentType
}).promise()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment