-
Notifications
You must be signed in to change notification settings - Fork 1
/
basic-tts.js
273 lines (233 loc) · 7.22 KB
/
basic-tts.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
273
"use strict";
const tts = (() => {
let testWindow;
let testingEnabled = false;
/**
* Enable test mode.
*
* @param {Object=} mockWindow - The mock window object.
*/
const enableTesting = (mockWindow) => {
testWindow = mockWindow;
testingEnabled = true;
};
/**
* Disable test mode and return to production mode.
*/
const disableTesting = () => {
testWindow = null;
testingEnabled = false;
};
/**
* Check if we're in test mode or not.
*
* @returns {Boolean}
*/
const isTestingEnabled = () => (
testingEnabled
);
/**
* Get the window object, depending on whether we're in test mode or not.
*
* @returns {Window}
*/
const getWindow = () => (
isTestingEnabled() ? testWindow :
(typeof(window) === "undefined" ? undefined : window)
);
/**
* Check if text-to-speech is supported.
*
* @returns {Boolean} - Whether text-to-speech is supported.
*/
const isSupported = () => {
const window = getWindow();
if (typeof(window) !== "object") {
console.warn("window is undefined!");
return false;
}
if (typeof(window.speechSynthesis) !== "object") {
console.warn("speechSynthesis is undefined!");
return false;
}
for (const method of ["getVoices", "speak"]) {
if (typeof(window.speechSynthesis[method]) !== "function") {
console.warn(`speechSynthesis.${method} is undefined!`);
return false;
}
}
if (typeof(window.SpeechSynthesisUtterance) !== "function") {
console.warn("SpeechSynthesisUtterance is undefined!");
return false;
}
return true;
};
/**
* Check if text-to-speech is supported and error if it's not.
*/
const errOnUnsupported = () => {
if (!isSupported()) {
throw "Text-to-speech is not supported!";
}
};
/**
* Simple wrapper around a reject function for a Promise.
*
* @param {Function} reject - The Promise rejection function.
* @param {String} msg - The message to send.
*/
const rejectWithMsg = (reject, msg) => {
reject({ msg });
};
/**
* Get voices from speechSynthesis (after delay) and check if they exist.
*
* @returns {Promise}
*/
const loadVoices = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const voices = getWindow().speechSynthesis.getVoices();
if (voices.length === 0) {
rejectWithMsg(reject, "No voices available for use.");
} else {
resolve({
voices
});
}
}, 100);
});
};
/**
* Check that we have voices available for speaking.
*
* @param {Number=} attempts - The number of attempts to retrieve
* voices. The default is 10 times.
* @returns {Promise}
*/
const checkVoices = (attempts) => {
errOnUnsupported();
const defaultAttempts = 10;
if (typeof(attempts) === "undefined") {
attempts = defaultAttempts;
} else if (typeof(attempts) !== "number") {
attempts = parseInt(attempts.toString());
}
if (isNaN(attempts) || attempts < 0) {
attempts = defaultAttempts;
}
return loadVoices().catch((err) => {
if (attempts === 0) {
throw err;
} else {
return checkVoices(attempts - 1);
}
});
};
class Speaker {
/**
* Construct a new speaker instance.
*
* @param {Object=} props - A dictionary of properties for our
* SpeechSynthesisUtterance class.
*/
constructor(props) {
errOnUnsupported();
this._props = props || {};
this._window = getWindow();
this._speaker = this._window.speechSynthesis;
}
/**
* Construct our SpeechSynthesisUtterance for speaking.
*
* @param {String} text - The text to speak.
* @returns {SpeechSynthesisUtterance}
*/
getUtterance(text) {
const utterance = new this._window.SpeechSynthesisUtterance(text);
for (const key of ["lang", "volume", "pitch", "rate"]) {
const value = utterance[key];
utterance[key] = this._props[key] || value;
}
if (this._props["voice"]) {
const propVoice = this._props["voice"];
let speakerVoice;
for (const voice of this._speaker.getVoices()) {
if (voice.name === propVoice) {
speakerVoice = voice;
break;
}
}
if (speakerVoice === undefined) {
return null;
}
utterance.voice = speakerVoice;
}
return utterance;
}
/**
* Speak a piece of text.
*
* @param {String} text - The text to speak.
* @param {Number=} attempts - The number of attempts to retrieve
* voices before attempting to speak.
* @returns {Promise}
*/
speak(text, attempts) {
const self = this;
return new Promise((resolve, reject) => {
checkVoices(attempts).then(() => {
const utterance = self.getUtterance(text);
if (!utterance) {
rejectWithMsg(reject, "Speech could not be " +
"initialized due to invalid voice");
}
utterance["onend"] = resolve;
utterance["onerror"] = () => {
rejectWithMsg(reject, "Unable to speak " +
"the provided text");
};
self._speaker.speak(utterance);
}).catch(reject);
});
}
}
/**
* Convenience function for initialization our Speaker class.
*
* Doing this places an abstraction layer above the Speaker class, giving
* us freedom to modify however we want without disrupting end-user code.
*
* @param {Object=} props - A dictionary of properties for our
* SpeechSynthesisUtterance class.
* @returns {Speaker}
*/
const createSpeaker = (props) => (
new Speaker(props)
);
return {
// Main methods.
checkVoices,
isSupported,
createSpeaker,
// Test methods.
enableTesting,
disableTesting,
isTestingEnabled,
};
})();
// Node.
if (typeof(module) === "object" && typeof(module.exports) === "object") {
module.exports = tts;
}
// AMD.
//
// One of the following define calls should work.
if (typeof(define) === "function" && define.amd) {
define("basic-tts", [], () => {
return tts;
});
define([], () => {
return tts;
});
}