forked from ejbeaty/ChattyKathy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChattyKathy.js
277 lines (237 loc) · 8.11 KB
/
ChattyKathy.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*! ChattyKathy 1.0.1
* ©2016 Elliott Beaty
*/
/**
* @summary ChattyKathy
* @description Wrapper for Amazon's AWS Polly Javascript SDK
* @version 1.0.1
* @file ChattyKathy.js
* @author Elliott Beaty
* @contact [email protected]
* @copyright Copyright 2016 Elliott Beaty
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
*/
function ChattyKathy(settings) {
settings = getValidatedSettings(settings);
// Add audio node to html
var elementId = "audioElement" + new Date().valueOf().toString();
var audioElement = document.createElement('audio');
audioElement.setAttribute("id", elementId);
document.body.appendChild(audioElement);
var isSpeaking = false;
AWS.config.credentials = settings.awsCredentials;
AWS.config.region = settings.awsRegion;
var kathy = {
self: this,
playlist:[],
// Speak
copyS3File: function () { copyS3File(); },
Speak: function (msg) {
if (isSpeaking) {
this.playlist.push(msg);
} else {
say(msg).then(sayNext)
}
},
// Quit speaking, clear playlist
ShutUp: function(){
shutUp();
},
// Speak & return promise
SpeakWithPromise: function (msg) {
return say(msg);
},
IsSpeaking: function () {
return isSpeaking;
},
ForgetCachedSpeech: function () {
localStorage.removeItem("chattyKathyDictionary");
}
}
// Quit talking
function shutUp() {
isSpeaking = false;
audioElement.pause();
playlist = [];
}
// Speak the message
function say(message) {
return new Promise(function (successCallback, errorCallback) {
isSpeaking = true;
getAudio(message)
.then(playAudio)
.then(successCallback);
});
}
// Say next
function sayNext() {
var list = kathy.playlist;
if (list.length > 0) {
var msg = list[0];
list.splice(0, 1);
say(msg).then(sayNext);
}
}
// Get Audio
function getAudio(message) {
if (settings.cacheSpeech === false || requestSpeechFromLocalCache(message) === null) {
return requestSpeechFromAWS(message);
} else {
return requestSpeechFromLocalCache(message);
}
}
function renameFile(oldName, newName, callback) {
s3 = new AWS.S3();
var params = {
Bucket: 'flowaudio',
CopySource: "flowaudio/" + oldName + ".mp3",
Key: newName +'.mp3',
ACL: 'public-read'
};
s3.copyObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
}// an error occurred
else {
console.log(data);
params = {
Bucket: 'flowaudio',
Key: oldName + ".mp3",
};
s3.deleteObject(params, function(err, data) {
if (err) { console.log(err, err.stack);} // an error occurred
else {
callback();
console.log(data);
}
// successful response
});
}// successful response
});
}
// Make request to Amazon polly
function requestSpeechFromAWS(message) {
return new Promise(function (successCallback, errorCallback) {
var polly = new AWS.Polly();
var params = {
OutputFormat: 'mp3',
OutputS3BucketName: "flowaudio",
Engine: "neural",
Text: `<speak>${message}</speak>`,
VoiceId: settings.pollyVoiceId,
TextType: 'ssml'
}
polly.startSpeechSynthesisTask(params, function (error, data) {
if (error) {
errorCallback(error)
} else {
var x = 0;
var intervalID = window.setInterval(function () {
renameFile(data.SynthesisTask.TaskId, message.replace(/\s/g, "-"), function () {
window.clearInterval(intervalID);
console.log("all clear!");
});
if (++x === 10) {
window.clearInterval(intervalID);
console.log("failed to rename");
}
}, 5000);
console.log("finished");
window.mytask = data;
console.log(data);
console.log(window.mytask);
}
});
params = {
OutputFormat: 'mp3',
Engine: "neural",
Text: `<speak>${message}</speak>`,
VoiceId: settings.pollyVoiceId,
TextType: 'ssml'
}
polly.synthesizeSpeech(params, function (error, data) {
if (error) {
errorCallback(error)
} else {
saveSpeechToLocalCache(message, data.AudioStream);
successCallback(data.AudioStream);
}
});
});
}
// Save to local cache
function saveSpeechToLocalCache(message, audioStream) {
var record = {
Message: message,
AudioStream: JSON.stringify(audioStream)
};
var localPlaylist = JSON.parse(localStorage.getItem("chattyKathyDictionary"));
if (localPlaylist === null) {
localPlaylist = [];
localPlaylist.push(record);
}else{
localPlaylist.push(record);
}
localStorage.setItem("chattyKathyDictionary", JSON.stringify(localPlaylist));
}
// Check local cache for audio clip
function requestSpeechFromLocalCache(message) {
var audioDictionary = localStorage.getItem("chattyKathyDictionary");
if (audioDictionary === null) {
return null;
}
var audioStreamArray = JSON.parse(audioDictionary);
var audioStream = audioStreamArray.filter(function (record) {
return record.Message === message;
})[0];
if (audioStream === null || typeof audioStream === 'undefined') {
return null;
} else {
return new Promise(function (successCallback, errorCallback) {
successCallback(JSON.parse(audioStream.AudioStream).data);
});
}
}
// Play audio
function playAudio(audioStream) {
return new Promise(function (success, error) {
var uInt8Array = new Uint8Array(audioStream);
var arrayBuffer = uInt8Array.buffer;
var blob = new Blob([arrayBuffer]);
var url = URL.createObjectURL(blob);
audioElement.src = url;
audioElement.addEventListener("ended", function () {
isSpeaking = false;
success();
});
audioElement.play();
});
}
// Validate settings
function getValidatedSettings(settings) {
if (typeof settings === 'undefined') {
throw "Settings must be provided to ChattyKathy's constructor";
}
if (typeof settings.awsCredentials === 'undefined') {
throw "A valid AWS Credentials object must be provided";
}
if (typeof settings.awsRegion === 'undefined' || settings.awsRegion.length < 1) {
throw "A valid AWS Region must be provided";
}
if (typeof settings.pollyVoiceId === 'undefined') {
settings.pollyVoiceId = "Amy";
}
if (typeof settings.cacheSpeech === 'undefined') {
settings.cacheSpeech === true;
}
return settings;
}
return kathy;
}