forked from nativescript-community/texttospeech
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtexttospeech.android.ts
248 lines (218 loc) · 7.61 KB
/
texttospeech.android.ts
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
import * as appModule from "tns-core-modules/application";
import { SpeakOptions, Language } from "./index";
declare var android, java: any;
const Locale = java.util.Locale;
export class TNSTextToSpeech {
private _tts: any; /// android.speech.tts.TextToSpeech
private _initialized: boolean = false;
private _lastOptions: SpeakOptions = null; // saves a reference to the last passed SpeakOptions for pause/resume/callback methods.
private _utteranceProgressListener = android.speech.tts.UtteranceProgressListener.extend(
{
init: () => {
// console.log("UtteranceProgressListener created!");
},
onStart: (utteranceId: string) => {
// TODO
},
onError: (utteranceId: string) => {
// TODO
},
onDone: (utteranceId: string) => {
if (this._lastOptions.finishedCallback) {
this._lastOptions.finishedCallback();
}
}
}
);
private init(): Promise<any> {
return new Promise((resolve, reject) => {
if (!this._tts || !this._initialized) {
this._tts = new android.speech.tts.TextToSpeech(
this._getContext(),
new android.speech.tts.TextToSpeech.OnInitListener({
onInit: status => {
// if the TextToSpeech was successful initializing
if (status === android.speech.tts.TextToSpeech.SUCCESS) {
this._initialized = true;
this._tts.setOnUtteranceProgressListener(
new this._utteranceProgressListener()
);
resolve();
} else {
reject(status);
}
}
})
);
} else {
resolve();
}
});
}
public speak(options: SpeakOptions): Promise<any> {
return new Promise((resolve, reject) => {
if (!this.isString(options.text)) {
reject("Text property is required to speak.");
return;
}
this.init().then(
() => {
let maxLen: number = 4000; // API level 18 added method for getting value dynamically
if (android.os.Build.VERSION.SDK_INT >= 18) {
try {
maxLen = this._tts.getMaxSpeechInputLength();
} catch (error) {
//console.log(error);
}
}
if (options.text.length > maxLen) {
reject(
"Text cannot be greater than " + maxLen.toString() + " characters"
);
return;
}
// save a reference to the options passed in for pause/resume methods to use
this._lastOptions = options;
this.speakText(options);
resolve();
},
err => {
reject(err);
}
);
});
}
/**
* Interrupts the current utterance and discards other utterances in the queue.
* https://developer.android.com/reference/android/speech/tts/TextToSpeech.html#stop()
*/
public pause() {
if (this._tts && this._initialized) {
this._tts.stop();
}
}
public resume() {
//In Android there's no pause so we resume playng the last phrase...
if (this._lastOptions) {
this.speak(this._lastOptions);
}
}
/**
* Releases the resources used by the TextToSpeech engine.
* https://developer.android.com/reference/android/speech/tts/TextToSpeech.html#shutdown()
*/
public destroy() {
if (this._tts) {
this._tts.shutdown();
}
}
private speakText(options: SpeakOptions) {
if (this.isString(options.locale) && this.isValidLocale(options.locale)) {
let localeArray = options.locale.split("-");
let locale = new Locale(localeArray[0], localeArray[1]);
this._tts.setLanguage(locale);
} else if (this.isString(options.language)) {
let locale = null;
if (this.isValidLocale(options.language)) {
// only for backwards compatbility with old API
let languageArray = options.language.split("-");
locale = new Locale(languageArray[0], languageArray[1]);
} else {
locale = new Locale(options.language);
}
if (locale) {
this._tts.setLanguage(locale);
}
}
if (!this.isBoolean(options.queue)) {
options.queue = false;
}
if (!options.queue && this._tts.isSpeaking()) {
this._tts.stop();
}
// no range of valid values for Android so just cover default value if none provided
if (!this.isNumber(options.pitch)) {
options.pitch = 1.0;
}
// no range of valid values for Android so just cover default value if none provided
if (!this.isNumber(options.speakRate)) {
options.speakRate = 1.0;
}
// valid values are 0.0 to 1.0
if (!this.isNumber(options.volume) || options.volume > 1.0) {
options.volume = 1.0;
} else if (options.volume < 0.0) {
options.volume = 0.0;
}
this._tts.setPitch(options.pitch);
this._tts.setSpeechRate(options.speakRate);
let queueMode = options.queue
? android.speech.tts.TextToSpeech.QUEUE_ADD
: android.speech.tts.TextToSpeech.QUEUE_FLUSH;
if (android.os.Build.VERSION.SDK_INT >= 21) {
// Hardcoded this value since the static field LOLLIPOP doesn't exist in Android 4.4
/// >= Android API 21 - https://developer.android.com/reference/android/speech/tts/TextToSpeech.html#speak(java.lang.CharSequence, int, android.os.Bundle, java.lang.String)
let params = new android.os.Bundle();
params.putString("volume", options.volume.toString());
this._tts.speak(options.text, queueMode, params, "UniqueID");
} else {
/// < Android API 21 - https://developer.android.com/reference/android/speech/tts/TextToSpeech.html#speak(java.lang.String, int, java.util.HashMap<java.lang.String, java.lang.String>)
let hashMap = new java.util.HashMap();
hashMap.put("volume", options.volume.toString());
this._tts.speak(options.text, queueMode, hashMap);
}
}
public getAvailableLanguages(): Promise<Array<Language>> {
return new Promise((resolve, reject) => {
let result: Array<Language> = new Array<Language>();
this.init().then(
() => {
var languages = this._tts.getAvailableLanguages().toArray();
for (var c = 0; c < languages.length; c++) {
let lang: Language = {
language: languages[c].getLanguage(),
languageDisplay: languages[c].getDisplayLanguage(),
country: languages[c].getCountry(),
countryDisplay: languages[c].getDisplayCountry()
};
result.push(lang);
}
resolve(result);
},
err => {
reject(err);
}
);
});
}
// helper function to get current app context
private _getContext() {
if (appModule.android.context) {
return appModule.android.context;
}
var ctx = java.lang.Class
.forName("android.app.AppGlobals")
.getMethod("getInitialApplication", null)
.invoke(null, null);
if (ctx) return ctx;
ctx = java.lang.Class
.forName("android.app.ActivityThread")
.getMethod("currentApplication", null)
.invoke(null, null);
return ctx;
}
// helper function to test whether language code has valid syntax
private isValidLocale(locale) {
var re = new RegExp("\\w\\w-\\w\\w");
return re.test(locale);
}
private isString(elem) {
return Object.prototype.toString.call(elem).slice(8, -1) === "String";
}
private isBoolean(elem) {
return Object.prototype.toString.call(elem).slice(8, -1) === "Boolean";
}
private isNumber(elem) {
return Object.prototype.toString.call(elem).slice(8, -1) === "Number";
}
}