Automatically Converting Your Text Files to Speech MP3s w/ AWS Polly https://www.aaronmedacco.com/blog/post/2017/01/21/automatically-converting-your-text-files-to-speech-mp3s-w-aws-polly
var AWS = require("aws-sdk");
exports.handler = (event, context, callback) => {
var s3 = new AWS.S3();
var polly = new AWS.Polly();
var destinationBucket = "Destination Bucket Name";
var params = {
Bucket: event.Records[0].s3.bucket.name,
Key: event.Records[0].s3.object.key
};
s3.getObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
}
else {
var objectKey = event.Records[0].s3.object.key;
var objectNameMp3 = objectKey.replace(".txt", ".mp3");
var pollyParams = {
OutputFormat: "mp3",
SampleRate: "8000",
Text: data.Body.toString('utf-8'),
TextType: "text",
VoiceId: "Joanna"
};
polly.synthesizeSpeech(pollyParams, function(err, data) {
if (err) {
console.log(err, err.stack);
}
else {
var uploadParam = { Bucket: destinationBucket, Key: objectNameMp3, Body: data.AudioStream, ContentType: "audio/mpeg", StorageClass: "STANDARD" };
s3.upload(uploadParam, function(err, data) {
if (err) {
console.log(err, err.stack);
} else{
console.log("Speech file upload successful.")
}
});
}
});
}
});
};
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"polly:SynthesizeSpeech"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"Your Source Bucket ARN/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": [
"Your Destination Bucket ARN/*"
]
}
]
}