-
Notifications
You must be signed in to change notification settings - Fork 23
/
ChattyKathy.js
210 lines (177 loc) · 6.01 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
/*! 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 elliott@elliottbeaty.com
* @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
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);
}
}
// Make request to Amazon polly
function requestSpeechFromAWS(message) {
return new Promise(function (successCallback, errorCallback) {
var polly = new AWS.Polly();
var params = {
OutputFormat: 'mp3',
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;
}