-
Notifications
You must be signed in to change notification settings - Fork 464
/
Copy pathaws-polly.js
72 lines (62 loc) · 1.97 KB
/
aws-polly.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const path = require('path');
const AWS = require('aws-sdk');
const fileDuration = require('../helpers/file-duration');
const settings = require('../../settings');
const logger = require('sonos-discovery/lib/helpers/logger');
const DEFAULT_SETTINGS = {
OutputFormat: 'mp3',
VoiceId: 'Joanna',
TextType: 'text'
};
function polly(phrase, voiceName) {
if (!settings.aws) {
return Promise.resolve();
}
// Construct a filesystem neutral filename
const dynamicParameters = { Text: phrase };
const synthesizeParameters = Object.assign({}, DEFAULT_SETTINGS, dynamicParameters);
if (phrase.startsWith('<speak>') && phrase.endsWith('</speak>')) {
synthesizeParameters.TextType = 'ssml';
}
if (settings.aws.name) {
synthesizeParameters.VoiceId = settings.aws.name;
}
if (voiceName) {
synthesizeParameters.VoiceId = voiceName;
}
const phraseHash = crypto.createHash('sha1').update(phrase).digest('hex');
const filename = `polly-${phraseHash}-${synthesizeParameters.VoiceId}.mp3`;
const filepath = path.resolve(settings.webroot, 'tts', filename);
const expectedUri = `/tts/${filename}`;
try {
fs.accessSync(filepath, fs.R_OK);
return fileDuration(filepath)
.then((duration) => {
return {
duration,
uri: expectedUri
};
});
} catch (err) {
logger.info(`announce file for phrase "${phrase}" does not seem to exist, downloading`);
}
const constructorParameters = Object.assign({ apiVersion: '2016-06-10' }, settings.aws.credentials);
const polly = new AWS.Polly(constructorParameters);
return polly.synthesizeSpeech(synthesizeParameters)
.promise()
.then((data) => {
fs.writeFileSync(filepath, data.AudioStream);
return fileDuration(filepath);
})
.then((duration) => {
return {
duration,
uri: expectedUri
};
});
}
module.exports = polly;