web-speech-cognitive-services 7.1.4-master.9e026d9 → 8.0.0-main.85313be

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/web-speech-cognitive-services.d.mts +186 -0
  2. package/dist/web-speech-cognitive-services.d.ts +186 -0
  3. package/dist/web-speech-cognitive-services.development.js +25677 -0
  4. package/dist/web-speech-cognitive-services.development.js.map +1 -0
  5. package/dist/web-speech-cognitive-services.js +1267 -0
  6. package/dist/web-speech-cognitive-services.js.map +1 -0
  7. package/dist/web-speech-cognitive-services.mjs +1232 -0
  8. package/dist/web-speech-cognitive-services.mjs.map +1 -0
  9. package/dist/web-speech-cognitive-services.production.min.js +31 -0
  10. package/dist/web-speech-cognitive-services.production.min.js.map +1 -0
  11. package/package.json +54 -40
  12. package/CHANGELOG.md +0 -372
  13. package/lib/BingSpeech/SpeechToText/SpeechGrammarList.js +0 -94
  14. package/lib/BingSpeech/SpeechToText/SpeechGrammarList.js.map +0 -1
  15. package/lib/BingSpeech/SpeechToText/createSpeechRecognitionPonyfill.js +0 -483
  16. package/lib/BingSpeech/SpeechToText/createSpeechRecognitionPonyfill.js.map +0 -1
  17. package/lib/BingSpeech/SpeechToText.js +0 -14
  18. package/lib/BingSpeech/SpeechToText.js.map +0 -1
  19. package/lib/BingSpeech/TextToSpeech/AudioContextConsumer.js +0 -122
  20. package/lib/BingSpeech/TextToSpeech/AudioContextConsumer.js.map +0 -1
  21. package/lib/BingSpeech/TextToSpeech/AudioContextQueue.js +0 -104
  22. package/lib/BingSpeech/TextToSpeech/AudioContextQueue.js.map +0 -1
  23. package/lib/BingSpeech/TextToSpeech/SpeechSynthesisUtterance.js +0 -264
  24. package/lib/BingSpeech/TextToSpeech/SpeechSynthesisUtterance.js.map +0 -1
  25. package/lib/BingSpeech/TextToSpeech/SpeechSynthesisVoice.js +0 -61
  26. package/lib/BingSpeech/TextToSpeech/SpeechSynthesisVoice.js.map +0 -1
  27. package/lib/BingSpeech/TextToSpeech/buildSSML.js +0 -32
  28. package/lib/BingSpeech/TextToSpeech/buildSSML.js.map +0 -1
  29. package/lib/BingSpeech/TextToSpeech/createSpeechSynthesisPonyfill.js +0 -220
  30. package/lib/BingSpeech/TextToSpeech/createSpeechSynthesisPonyfill.js.map +0 -1
  31. package/lib/BingSpeech/TextToSpeech/fetchSpeechData.js +0 -74
  32. package/lib/BingSpeech/TextToSpeech/fetchSpeechData.js.map +0 -1
  33. package/lib/BingSpeech/TextToSpeech/fetchVoices.js +0 -335
  34. package/lib/BingSpeech/TextToSpeech/fetchVoices.js.map +0 -1
  35. package/lib/BingSpeech/TextToSpeech/isSSML.js +0 -13
  36. package/lib/BingSpeech/TextToSpeech/isSSML.js.map +0 -1
  37. package/lib/BingSpeech/TextToSpeech/subscribeEvent.js +0 -14
  38. package/lib/BingSpeech/TextToSpeech/subscribeEvent.js.map +0 -1
  39. package/lib/BingSpeech/TextToSpeech.js +0 -14
  40. package/lib/BingSpeech/TextToSpeech.js.map +0 -1
  41. package/lib/BingSpeech/Util/DOMEventEmitter.js +0 -61
  42. package/lib/BingSpeech/Util/DOMEventEmitter.js.map +0 -1
  43. package/lib/BingSpeech/Util/createFetchTokenUsingSubscriptionKey.js +0 -41
  44. package/lib/BingSpeech/Util/createFetchTokenUsingSubscriptionKey.js.map +0 -1
  45. package/lib/BingSpeech/fetchAuthorizationToken.js +0 -57
  46. package/lib/BingSpeech/fetchAuthorizationToken.js.map +0 -1
  47. package/lib/BingSpeech/index.js +0 -84
  48. package/lib/BingSpeech/index.js.map +0 -1
  49. package/lib/SpeechServices/SpeechSDK.js +0 -19
  50. package/lib/SpeechServices/SpeechSDK.js.map +0 -1
  51. package/lib/SpeechServices/SpeechToText/SpeechGrammarList.js +0 -45
  52. package/lib/SpeechServices/SpeechToText/SpeechGrammarList.js.map +0 -1
  53. package/lib/SpeechServices/SpeechToText/cognitiveServiceEventResultToWebSpeechRecognitionResultList.js +0 -56
  54. package/lib/SpeechServices/SpeechToText/cognitiveServiceEventResultToWebSpeechRecognitionResultList.js.map +0 -1
  55. package/lib/SpeechServices/SpeechToText/createSpeechRecognitionPonyfill.js +0 -984
  56. package/lib/SpeechServices/SpeechToText/createSpeechRecognitionPonyfill.js.map +0 -1
  57. package/lib/SpeechServices/SpeechToText.js +0 -24
  58. package/lib/SpeechServices/SpeechToText.js.map +0 -1
  59. package/lib/SpeechServices/TextToSpeech/AudioContextConsumer.js +0 -92
  60. package/lib/SpeechServices/TextToSpeech/AudioContextConsumer.js.map +0 -1
  61. package/lib/SpeechServices/TextToSpeech/AudioContextQueue.js +0 -111
  62. package/lib/SpeechServices/TextToSpeech/AudioContextQueue.js.map +0 -1
  63. package/lib/SpeechServices/TextToSpeech/SpeechSynthesisEvent.js +0 -40
  64. package/lib/SpeechServices/TextToSpeech/SpeechSynthesisEvent.js.map +0 -1
  65. package/lib/SpeechServices/TextToSpeech/SpeechSynthesisUtterance.js +0 -283
  66. package/lib/SpeechServices/TextToSpeech/SpeechSynthesisUtterance.js.map +0 -1
  67. package/lib/SpeechServices/TextToSpeech/SpeechSynthesisVoice.js +0 -63
  68. package/lib/SpeechServices/TextToSpeech/SpeechSynthesisVoice.js.map +0 -1
  69. package/lib/SpeechServices/TextToSpeech/buildSSML.js +0 -32
  70. package/lib/SpeechServices/TextToSpeech/buildSSML.js.map +0 -1
  71. package/lib/SpeechServices/TextToSpeech/createSpeechSynthesisPonyfill.js +0 -282
  72. package/lib/SpeechServices/TextToSpeech/createSpeechSynthesisPonyfill.js.map +0 -1
  73. package/lib/SpeechServices/TextToSpeech/fetchCustomVoices.js +0 -110
  74. package/lib/SpeechServices/TextToSpeech/fetchCustomVoices.js.map +0 -1
  75. package/lib/SpeechServices/TextToSpeech/fetchSpeechData.js +0 -127
  76. package/lib/SpeechServices/TextToSpeech/fetchSpeechData.js.map +0 -1
  77. package/lib/SpeechServices/TextToSpeech/fetchVoices.js +0 -87
  78. package/lib/SpeechServices/TextToSpeech/fetchVoices.js.map +0 -1
  79. package/lib/SpeechServices/TextToSpeech/isSSML.js +0 -13
  80. package/lib/SpeechServices/TextToSpeech/isSSML.js.map +0 -1
  81. package/lib/SpeechServices/TextToSpeech/subscribeEvent.js +0 -14
  82. package/lib/SpeechServices/TextToSpeech/subscribeEvent.js.map +0 -1
  83. package/lib/SpeechServices/TextToSpeech.js +0 -14
  84. package/lib/SpeechServices/TextToSpeech.js.map +0 -1
  85. package/lib/SpeechServices/fetchAuthorizationToken.js +0 -58
  86. package/lib/SpeechServices/fetchAuthorizationToken.js.map +0 -1
  87. package/lib/SpeechServices/patchOptions.js +0 -213
  88. package/lib/SpeechServices/patchOptions.js.map +0 -1
  89. package/lib/SpeechServices/resolveFunctionOrReturnValue.js +0 -11
  90. package/lib/SpeechServices/resolveFunctionOrReturnValue.js.map +0 -1
  91. package/lib/SpeechServices.js +0 -73
  92. package/lib/SpeechServices.js.map +0 -1
  93. package/lib/Util/arrayToMap.js +0 -28
  94. package/lib/Util/arrayToMap.js.map +0 -1
  95. package/lib/Util/createPromiseQueue.js +0 -40
  96. package/lib/Util/createPromiseQueue.js.map +0 -1
  97. package/lib/index.js +0 -14
  98. package/lib/index.js.map +0 -1
  99. package/umd/web-speech-cognitive-services.development.js +0 -4740
  100. package/umd/web-speech-cognitive-services.production.min.js +0 -2
@@ -0,0 +1,1267 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.js
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ createSpeechRecognitionPonyfill: () => SpeechToText_default,
34
+ createSpeechRecognitionPonyfillFromRecognizer: () => createSpeechRecognitionPonyfillFromRecognizer,
35
+ createSpeechServicesPonyfill: () => createSpeechServicesPonyfill,
36
+ createSpeechSynthesisPonyfill: () => TextToSpeech_default,
37
+ fetchAuthorizationToken: () => fetchAuthorizationToken_default
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // src/SpeechServices/SpeechToText/createSpeechRecognitionPonyfill.js
42
+ var import_event_target_shim = require("event-target-shim");
43
+
44
+ // src/Util/arrayToMap.js
45
+ function arrayToMap_default(array, extras) {
46
+ const map = {
47
+ ...[].reduce.call(
48
+ array,
49
+ (map2, value, index) => {
50
+ map2[index] = value;
51
+ return map2;
52
+ },
53
+ {}
54
+ ),
55
+ ...extras,
56
+ length: array.length,
57
+ [Symbol.iterator]: () => [].slice.call(map)[Symbol.iterator]()
58
+ };
59
+ return map;
60
+ }
61
+
62
+ // src/SpeechServices/SpeechSDK.js
63
+ var import_microsoft_cognitiveservices_speech = require("microsoft-cognitiveservices-speech-sdk/distrib/lib/microsoft.cognitiveservices.speech.sdk");
64
+ var SpeechSDK_default = {
65
+ AudioConfig: import_microsoft_cognitiveservices_speech.AudioConfig,
66
+ OutputFormat: import_microsoft_cognitiveservices_speech.OutputFormat,
67
+ ResultReason: import_microsoft_cognitiveservices_speech.ResultReason,
68
+ SpeechConfig: import_microsoft_cognitiveservices_speech.SpeechConfig,
69
+ SpeechRecognizer: import_microsoft_cognitiveservices_speech.SpeechRecognizer
70
+ };
71
+
72
+ // src/SpeechServices/SpeechToText/cognitiveServiceEventResultToWebSpeechRecognitionResultList.js
73
+ var {
74
+ ResultReason: { RecognizingSpeech, RecognizedSpeech }
75
+ } = SpeechSDK_default;
76
+ function cognitiveServiceEventResultToWebSpeechRecognitionResultList_default(result, { maxAlternatives = Infinity, textNormalization = "display" } = {}) {
77
+ if (result.reason === RecognizingSpeech || result.reason === RecognizedSpeech && !result.json.NBest) {
78
+ const resultList = [
79
+ {
80
+ confidence: 0.5,
81
+ transcript: result.text
82
+ }
83
+ ];
84
+ if (result.reason === RecognizedSpeech) {
85
+ resultList.isFinal = true;
86
+ }
87
+ return resultList;
88
+ } else if (result.reason === RecognizedSpeech) {
89
+ const resultList = arrayToMap_default(
90
+ (result.json.NBest || []).slice(0, maxAlternatives).map(({ Confidence: confidence, Display: display, ITN: itn, Lexical: lexical, MaskedITN: maskedITN }) => ({
91
+ confidence,
92
+ transcript: textNormalization === "itn" ? itn : textNormalization === "lexical" ? lexical : textNormalization === "maskeditn" ? maskedITN : display
93
+ })),
94
+ { isFinal: true }
95
+ );
96
+ return resultList;
97
+ }
98
+ return [];
99
+ }
100
+
101
+ // ../../node_modules/p-defer/index.js
102
+ function pDefer() {
103
+ const deferred = {};
104
+ deferred.promise = new Promise((resolve, reject) => {
105
+ deferred.resolve = resolve;
106
+ deferred.reject = reject;
107
+ });
108
+ return deferred;
109
+ }
110
+
111
+ // src/Util/createPromiseQueue.js
112
+ function createPromiseQueue_default() {
113
+ let shiftDeferred;
114
+ const queue = [];
115
+ const push = (value) => {
116
+ if (shiftDeferred) {
117
+ const { resolve } = shiftDeferred;
118
+ shiftDeferred = null;
119
+ resolve(value);
120
+ } else {
121
+ queue.push(value);
122
+ }
123
+ };
124
+ const shift = () => {
125
+ if (queue.length) {
126
+ return Promise.resolve(queue.shift());
127
+ }
128
+ return (shiftDeferred || (shiftDeferred = pDefer())).promise;
129
+ };
130
+ return {
131
+ push,
132
+ shift
133
+ };
134
+ }
135
+
136
+ // src/SpeechServices/resolveFunctionOrReturnValue.ts
137
+ function isFunction(value) {
138
+ return typeof value === "function";
139
+ }
140
+ function resolveFunctionOrReturnValue(fnOrValue) {
141
+ return isFunction(fnOrValue) ? fnOrValue() : fnOrValue;
142
+ }
143
+
144
+ // src/SpeechServices/patchOptions.js
145
+ var shouldWarnOnSubscriptionKey = true;
146
+ function patchOptions({
147
+ authorizationToken,
148
+ credentials,
149
+ looseEvent,
150
+ looseEvents,
151
+ region = "westus",
152
+ subscriptionKey,
153
+ ...otherOptions
154
+ } = {}) {
155
+ if (typeof looseEvent !== "undefined") {
156
+ console.warn('web-speech-cognitive-services: The option "looseEvent" should be named as "looseEvents".');
157
+ looseEvents = looseEvent;
158
+ }
159
+ if (!credentials) {
160
+ if (!authorizationToken && !subscriptionKey) {
161
+ throw new Error("web-speech-cognitive-services: Credentials must be specified.");
162
+ } else {
163
+ console.warn(
164
+ "web-speech-cognitive-services: We are deprecating authorizationToken, region, and subscriptionKey. Please use credentials instead. The deprecated option will be removed on or after 2020-11-14."
165
+ );
166
+ credentials = async () => authorizationToken ? { authorizationToken: await resolveFunctionOrReturnValue(authorizationToken), region } : { region, subscriptionKey: await resolveFunctionOrReturnValue(subscriptionKey) };
167
+ }
168
+ }
169
+ return {
170
+ ...otherOptions,
171
+ fetchCredentials: async () => {
172
+ const {
173
+ authorizationToken: authorizationToken2,
174
+ customVoiceHostname,
175
+ region: region2,
176
+ speechRecognitionHostname,
177
+ speechSynthesisHostname,
178
+ subscriptionKey: subscriptionKey2
179
+ } = await resolveFunctionOrReturnValue(credentials);
180
+ if (!authorizationToken2 && !subscriptionKey2 || authorizationToken2 && subscriptionKey2) {
181
+ throw new Error(
182
+ 'web-speech-cognitive-services: Either "authorizationToken" or "subscriptionKey" must be provided.'
183
+ );
184
+ } else if (!region2 && !(speechRecognitionHostname && speechSynthesisHostname)) {
185
+ throw new Error(
186
+ 'web-speech-cognitive-services: Either "region" or "speechRecognitionHostname" and "speechSynthesisHostname" must be set.'
187
+ );
188
+ } else if (region2 && (customVoiceHostname || speechRecognitionHostname || speechSynthesisHostname)) {
189
+ throw new Error(
190
+ 'web-speech-cognitive-services: Only either "region" or "customVoiceHostname", "speechRecognitionHostname" and "speechSynthesisHostname" can be set.'
191
+ );
192
+ } else if (authorizationToken2) {
193
+ if (typeof authorizationToken2 !== "string") {
194
+ throw new Error('web-speech-cognitive-services: "authorizationToken" must be a string.');
195
+ }
196
+ } else if (typeof subscriptionKey2 !== "string") {
197
+ throw new Error('web-speech-cognitive-services: "subscriptionKey" must be a string.');
198
+ }
199
+ if (shouldWarnOnSubscriptionKey && subscriptionKey2) {
200
+ console.warn(
201
+ "web-speech-cognitive-services: In production environment, subscription key should not be used, authorization token should be used instead."
202
+ );
203
+ shouldWarnOnSubscriptionKey = false;
204
+ }
205
+ const resolvedCredentials = authorizationToken2 ? { authorizationToken: authorizationToken2 } : { subscriptionKey: subscriptionKey2 };
206
+ if (region2) {
207
+ resolvedCredentials.region = region2;
208
+ } else {
209
+ resolvedCredentials.customVoiceHostname = customVoiceHostname;
210
+ resolvedCredentials.speechRecognitionHostname = speechRecognitionHostname;
211
+ resolvedCredentials.speechSynthesisHostname = speechSynthesisHostname;
212
+ }
213
+ return resolvedCredentials;
214
+ },
215
+ looseEvents
216
+ };
217
+ }
218
+
219
+ // src/SpeechServices/SpeechToText/SpeechGrammarList.js
220
+ var SpeechGrammarList_default = class {
221
+ constructor() {
222
+ this._phrases = [];
223
+ }
224
+ addFromString() {
225
+ throw new Error("JSGF is not supported");
226
+ }
227
+ get phrases() {
228
+ return this._phrases;
229
+ }
230
+ set phrases(value) {
231
+ if (Array.isArray(value)) {
232
+ this._phrases = value;
233
+ } else if (typeof value === "string") {
234
+ this._phrases = [value];
235
+ } else {
236
+ throw new Error(`The provided value is not an array or of type 'string'`);
237
+ }
238
+ }
239
+ };
240
+
241
+ // src/SpeechServices/SpeechToText/createSpeechRecognitionPonyfill.js
242
+ var { AudioConfig: AudioConfig2, OutputFormat: OutputFormat2, ResultReason: ResultReason2, SpeechConfig: SpeechConfig2, SpeechRecognizer: SpeechRecognizer2 } = SpeechSDK_default;
243
+ function serializeRecognitionResult({ duration, errorDetails, json, offset, properties, reason, resultId, text }) {
244
+ return {
245
+ duration,
246
+ errorDetails,
247
+ json: JSON.parse(json),
248
+ offset,
249
+ properties,
250
+ reason,
251
+ resultId,
252
+ text
253
+ };
254
+ }
255
+ function averageAmplitude(arrayBuffer) {
256
+ const array = new Int16Array(arrayBuffer);
257
+ return [].reduce.call(array, (averageAmplitude2, amplitude) => averageAmplitude2 + Math.abs(amplitude), 0) / array.length;
258
+ }
259
+ function cognitiveServicesAsyncToPromise(fn) {
260
+ return (...args) => new Promise((resolve, reject) => fn(...args, resolve, reject));
261
+ }
262
+ var SpeechRecognitionEvent = class extends import_event_target_shim.Event {
263
+ constructor(type, { data, emma, interpretation, resultIndex, results } = {}) {
264
+ super(type);
265
+ this.data = data;
266
+ this.emma = emma;
267
+ this.interpretation = interpretation;
268
+ this.resultIndex = resultIndex;
269
+ this.results = results;
270
+ }
271
+ };
272
+ function prepareAudioConfig(audioConfig) {
273
+ const originalAttach = audioConfig.attach;
274
+ const boundOriginalAttach = audioConfig.attach.bind(audioConfig);
275
+ let firstChunk;
276
+ let muted;
277
+ audioConfig.attach = async () => {
278
+ const reader = await boundOriginalAttach();
279
+ return {
280
+ ...reader,
281
+ read: async () => {
282
+ const chunk = await reader.read();
283
+ if (!firstChunk && averageAmplitude(chunk.buffer) > 150) {
284
+ audioConfig.events.onEvent({ name: "FirstAudibleChunk" });
285
+ firstChunk = true;
286
+ }
287
+ if (muted) {
288
+ return { buffer: new ArrayBuffer(0), isEnd: true, timeReceived: Date.now() };
289
+ }
290
+ return chunk;
291
+ }
292
+ };
293
+ };
294
+ return {
295
+ audioConfig,
296
+ pause: () => {
297
+ muted = true;
298
+ },
299
+ unprepare: () => {
300
+ audioConfig.attach = originalAttach;
301
+ }
302
+ };
303
+ }
304
+ function createSpeechRecognitionPonyfillFromRecognizer({
305
+ createRecognizer,
306
+ enableTelemetry,
307
+ looseEvents,
308
+ referenceGrammars,
309
+ textNormalization
310
+ }) {
311
+ SpeechRecognizer2.enableTelemetry(enableTelemetry !== false);
312
+ class SpeechRecognition extends import_event_target_shim.EventTarget {
313
+ constructor() {
314
+ super();
315
+ this._continuous = false;
316
+ this._interimResults = false;
317
+ this._lang = typeof window !== "undefined" ? window.document.documentElement.getAttribute("lang") || window.navigator.language : "en-US";
318
+ this._grammars = new SpeechGrammarList_default();
319
+ this._maxAlternatives = 1;
320
+ }
321
+ emitCognitiveServices(type, event) {
322
+ this.dispatchEvent(
323
+ new SpeechRecognitionEvent("cognitiveservices", {
324
+ data: {
325
+ ...event,
326
+ type
327
+ }
328
+ })
329
+ );
330
+ }
331
+ get continuous() {
332
+ return this._continuous;
333
+ }
334
+ set continuous(value) {
335
+ this._continuous = value;
336
+ }
337
+ get grammars() {
338
+ return this._grammars;
339
+ }
340
+ set grammars(value) {
341
+ if (value instanceof SpeechGrammarList_default) {
342
+ this._grammars = value;
343
+ } else {
344
+ throw new Error(`The provided value is not of type 'SpeechGrammarList'`);
345
+ }
346
+ }
347
+ get interimResults() {
348
+ return this._interimResults;
349
+ }
350
+ set interimResults(value) {
351
+ this._interimResults = value;
352
+ }
353
+ get maxAlternatives() {
354
+ return this._maxAlternatives;
355
+ }
356
+ set maxAlternatives(value) {
357
+ this._maxAlternatives = value;
358
+ }
359
+ get lang() {
360
+ return this._lang;
361
+ }
362
+ set lang(value) {
363
+ this._lang = value;
364
+ }
365
+ get onaudioend() {
366
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "audioend");
367
+ }
368
+ set onaudioend(value) {
369
+ (0, import_event_target_shim.setEventAttributeValue)(this, "audioend", value);
370
+ }
371
+ get onaudiostart() {
372
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "audiostart");
373
+ }
374
+ set onaudiostart(value) {
375
+ (0, import_event_target_shim.setEventAttributeValue)(this, "audiostart", value);
376
+ }
377
+ get oncognitiveservices() {
378
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "cognitiveservices");
379
+ }
380
+ set oncognitiveservices(value) {
381
+ (0, import_event_target_shim.setEventAttributeValue)(this, "cognitiveservices", value);
382
+ }
383
+ get onend() {
384
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "end");
385
+ }
386
+ set onend(value) {
387
+ (0, import_event_target_shim.setEventAttributeValue)(this, "end", value);
388
+ }
389
+ get onerror() {
390
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "error");
391
+ }
392
+ set onerror(value) {
393
+ (0, import_event_target_shim.setEventAttributeValue)(this, "error", value);
394
+ }
395
+ get onresult() {
396
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "result");
397
+ }
398
+ set onresult(value) {
399
+ (0, import_event_target_shim.setEventAttributeValue)(this, "result", value);
400
+ }
401
+ get onsoundend() {
402
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "soundend");
403
+ }
404
+ set onsoundend(value) {
405
+ (0, import_event_target_shim.setEventAttributeValue)(this, "soundend", value);
406
+ }
407
+ get onsoundstart() {
408
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "soundstart");
409
+ }
410
+ set onsoundstart(value) {
411
+ (0, import_event_target_shim.setEventAttributeValue)(this, "soundstart", value);
412
+ }
413
+ get onspeechend() {
414
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "speechend");
415
+ }
416
+ set onspeechend(value) {
417
+ (0, import_event_target_shim.setEventAttributeValue)(this, "speechend", value);
418
+ }
419
+ get onspeechstart() {
420
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "speechstart");
421
+ }
422
+ set onspeechstart(value) {
423
+ (0, import_event_target_shim.setEventAttributeValue)(this, "speechstart", value);
424
+ }
425
+ get onstart() {
426
+ return (0, import_event_target_shim.getEventAttributeValue)(this, "start");
427
+ }
428
+ set onstart(value) {
429
+ (0, import_event_target_shim.setEventAttributeValue)(this, "start", value);
430
+ }
431
+ start() {
432
+ this._startOnce().catch((err) => {
433
+ this.dispatchEvent(new ErrorEvent("error", { error: err, message: err && (err.stack || err.message) }));
434
+ });
435
+ }
436
+ async _startOnce() {
437
+ const recognizer = await createRecognizer(this.lang);
438
+ const { pause, unprepare } = prepareAudioConfig(recognizer.audioConfig);
439
+ try {
440
+ const queue = createPromiseQueue_default();
441
+ let soundStarted;
442
+ let speechStarted;
443
+ let stopping;
444
+ const { detach: detachAudioConfigEvent } = recognizer.audioConfig.events.attach((event) => {
445
+ const { name } = event;
446
+ if (name === "AudioSourceReadyEvent") {
447
+ queue.push({ audioSourceReady: {} });
448
+ } else if (name === "AudioSourceOffEvent") {
449
+ queue.push({ audioSourceOff: {} });
450
+ } else if (name === "FirstAudibleChunk") {
451
+ queue.push({ firstAudibleChunk: {} });
452
+ }
453
+ });
454
+ recognizer.canceled = (_, { errorDetails, offset, reason, sessionId }) => {
455
+ queue.push({
456
+ canceled: {
457
+ errorDetails,
458
+ offset,
459
+ reason,
460
+ sessionId
461
+ }
462
+ });
463
+ };
464
+ recognizer.recognized = (_, { offset, result, sessionId }) => {
465
+ queue.push({
466
+ recognized: {
467
+ offset,
468
+ result: serializeRecognitionResult(result),
469
+ sessionId
470
+ }
471
+ });
472
+ };
473
+ recognizer.recognizing = (_, { offset, result, sessionId }) => {
474
+ queue.push({
475
+ recognizing: {
476
+ offset,
477
+ result: serializeRecognitionResult(result),
478
+ sessionId
479
+ }
480
+ });
481
+ };
482
+ recognizer.sessionStarted = (_, { sessionId }) => {
483
+ queue.push({ sessionStarted: { sessionId } });
484
+ };
485
+ recognizer.sessionStopped = (_, { sessionId }) => {
486
+ queue.push({ sessionStopped: { sessionId } });
487
+ };
488
+ recognizer.speechStartDetected = (_, { offset, sessionId }) => {
489
+ queue.push({ speechStartDetected: { offset, sessionId } });
490
+ };
491
+ recognizer.speechEndDetected = (_, { sessionId }) => {
492
+ queue.push({ speechEndDetected: { sessionId } });
493
+ };
494
+ const { phrases } = this.grammars;
495
+ const { dynamicGrammar } = recognizer.privReco;
496
+ referenceGrammars && referenceGrammars.length && dynamicGrammar.addReferenceGrammar(referenceGrammars);
497
+ phrases && phrases.length && dynamicGrammar.addPhrase(phrases);
498
+ await cognitiveServicesAsyncToPromise(recognizer.startContinuousRecognitionAsync.bind(recognizer))();
499
+ if (recognizer.stopContinuousRecognitionAsync) {
500
+ this.abort = () => queue.push({ abort: {} });
501
+ this.stop = () => queue.push({ stop: {} });
502
+ } else {
503
+ this.abort = this.stop = void 0;
504
+ }
505
+ let audioStarted;
506
+ let finalEvent;
507
+ let finalizedResults = [];
508
+ for (let loop = 0; !stopping || audioStarted; loop++) {
509
+ const event = await queue.shift();
510
+ const {
511
+ abort,
512
+ audioSourceOff,
513
+ audioSourceReady,
514
+ canceled,
515
+ firstAudibleChunk,
516
+ recognized,
517
+ recognizing,
518
+ stop
519
+ } = event;
520
+ Object.keys(event).forEach((name) => this.emitCognitiveServices(name, event[name]));
521
+ const errorMessage = canceled && canceled.errorDetails;
522
+ if (/Permission\sdenied/u.test(errorMessage || "")) {
523
+ finalEvent = {
524
+ error: "not-allowed",
525
+ type: "error"
526
+ };
527
+ break;
528
+ }
529
+ if (!loop) {
530
+ this.dispatchEvent(new SpeechRecognitionEvent("start"));
531
+ }
532
+ if (errorMessage) {
533
+ if (/1006/u.test(errorMessage)) {
534
+ if (!audioStarted) {
535
+ this.dispatchEvent(new SpeechRecognitionEvent("audiostart"));
536
+ this.dispatchEvent(new SpeechRecognitionEvent("audioend"));
537
+ }
538
+ finalEvent = {
539
+ error: "network",
540
+ type: "error"
541
+ };
542
+ } else {
543
+ finalEvent = {
544
+ error: "unknown",
545
+ type: "error"
546
+ };
547
+ }
548
+ break;
549
+ } else if (abort || stop) {
550
+ if (abort) {
551
+ finalEvent = {
552
+ error: "aborted",
553
+ type: "error"
554
+ };
555
+ stopping = "abort";
556
+ } else {
557
+ pause();
558
+ stopping = "stop";
559
+ }
560
+ if (abort && recognizer.stopContinuousRecognitionAsync) {
561
+ await cognitiveServicesAsyncToPromise(recognizer.stopContinuousRecognitionAsync.bind(recognizer))();
562
+ }
563
+ } else if (audioSourceReady) {
564
+ this.dispatchEvent(new SpeechRecognitionEvent("audiostart"));
565
+ audioStarted = true;
566
+ } else if (firstAudibleChunk) {
567
+ this.dispatchEvent(new SpeechRecognitionEvent("soundstart"));
568
+ soundStarted = true;
569
+ } else if (audioSourceOff) {
570
+ speechStarted && this.dispatchEvent(new SpeechRecognitionEvent("speechend"));
571
+ soundStarted && this.dispatchEvent(new SpeechRecognitionEvent("soundend"));
572
+ audioStarted && this.dispatchEvent(new SpeechRecognitionEvent("audioend"));
573
+ audioStarted = soundStarted = speechStarted = false;
574
+ break;
575
+ } else if (stopping !== "abort") {
576
+ if (recognized && recognized.result && recognized.result.reason === ResultReason2.NoMatch) {
577
+ finalEvent = {
578
+ error: "no-speech",
579
+ type: "error"
580
+ };
581
+ } else if (recognized || recognizing) {
582
+ if (!audioStarted) {
583
+ this.dispatchEvent(new SpeechRecognitionEvent("audiostart"));
584
+ audioStarted = true;
585
+ }
586
+ if (!soundStarted) {
587
+ this.dispatchEvent(new SpeechRecognitionEvent("soundstart"));
588
+ soundStarted = true;
589
+ }
590
+ if (!speechStarted) {
591
+ this.dispatchEvent(new SpeechRecognitionEvent("speechstart"));
592
+ speechStarted = true;
593
+ }
594
+ if (recognized) {
595
+ const result = cognitiveServiceEventResultToWebSpeechRecognitionResultList_default(recognized.result, {
596
+ maxAlternatives: this.maxAlternatives,
597
+ textNormalization
598
+ });
599
+ const recognizable = !!result[0].transcript;
600
+ if (recognizable) {
601
+ finalizedResults = [...finalizedResults, result];
602
+ this.continuous && this.dispatchEvent(
603
+ new SpeechRecognitionEvent("result", {
604
+ results: finalizedResults
605
+ })
606
+ );
607
+ }
608
+ if (this.continuous && recognizable) {
609
+ finalEvent = null;
610
+ } else {
611
+ finalEvent = {
612
+ results: finalizedResults,
613
+ type: "result"
614
+ };
615
+ }
616
+ if (!this.continuous && recognizer.stopContinuousRecognitionAsync) {
617
+ await cognitiveServicesAsyncToPromise(recognizer.stopContinuousRecognitionAsync.bind(recognizer))();
618
+ }
619
+ if (looseEvents && finalEvent && recognizable) {
620
+ this.dispatchEvent(new SpeechRecognitionEvent(finalEvent.type, finalEvent));
621
+ finalEvent = null;
622
+ }
623
+ } else if (recognizing) {
624
+ this.interimResults && this.dispatchEvent(
625
+ new SpeechRecognitionEvent("result", {
626
+ results: [
627
+ ...finalizedResults,
628
+ cognitiveServiceEventResultToWebSpeechRecognitionResultList_default(recognizing.result, {
629
+ maxAlternatives: this.maxAlternatives,
630
+ textNormalization
631
+ })
632
+ ]
633
+ })
634
+ );
635
+ }
636
+ }
637
+ }
638
+ }
639
+ if (speechStarted) {
640
+ this.dispatchEvent(new SpeechRecognitionEvent("speechend"));
641
+ }
642
+ if (soundStarted) {
643
+ this.dispatchEvent(new SpeechRecognitionEvent("soundend"));
644
+ }
645
+ if (audioStarted) {
646
+ this.dispatchEvent(new SpeechRecognitionEvent("audioend"));
647
+ }
648
+ if (finalEvent) {
649
+ if (finalEvent.type === "result" && !finalEvent.results.length) {
650
+ finalEvent = {
651
+ error: "no-speech",
652
+ type: "error"
653
+ };
654
+ }
655
+ if (finalEvent.type === "error") {
656
+ this.dispatchEvent(new ErrorEvent("error", finalEvent));
657
+ } else {
658
+ this.dispatchEvent(new SpeechRecognitionEvent(finalEvent.type, finalEvent));
659
+ }
660
+ }
661
+ this.dispatchEvent(new SpeechRecognitionEvent("end"));
662
+ detachAudioConfigEvent();
663
+ } catch (err) {
664
+ console.error(err);
665
+ throw err;
666
+ } finally {
667
+ unprepare();
668
+ recognizer.dispose();
669
+ }
670
+ }
671
+ }
672
+ return {
673
+ SpeechGrammarList: SpeechGrammarList_default,
674
+ SpeechRecognition,
675
+ SpeechRecognitionEvent
676
+ };
677
+ }
678
+ var createSpeechRecognitionPonyfill_default = (options) => {
679
+ const {
680
+ audioConfig = AudioConfig2.fromDefaultMicrophoneInput(),
681
+ // We set telemetry to true to honor the default telemetry settings of Speech SDK
682
+ // https://github.com/Microsoft/cognitive-services-speech-sdk-js#data--telemetry
683
+ enableTelemetry = true,
684
+ fetchCredentials,
685
+ looseEvents,
686
+ referenceGrammars,
687
+ speechRecognitionEndpointId,
688
+ textNormalization = "display"
689
+ } = patchOptions(options);
690
+ if (!audioConfig && (!window.navigator.mediaDevices || !window.navigator.mediaDevices.getUserMedia)) {
691
+ console.warn(
692
+ "web-speech-cognitive-services: This browser does not support WebRTC and it will not work with Cognitive Services Speech Services."
693
+ );
694
+ return {};
695
+ }
696
+ const createRecognizer = async (lang) => {
697
+ const { authorizationToken, region, speechRecognitionHostname, subscriptionKey } = await fetchCredentials();
698
+ let speechConfig;
699
+ if (speechRecognitionHostname) {
700
+ const host = { hostname: speechRecognitionHostname, port: 443, protocol: "wss:" };
701
+ if (authorizationToken) {
702
+ speechConfig = SpeechConfig2.fromHost(host);
703
+ speechConfig.authorizationToken = authorizationToken;
704
+ } else {
705
+ speechConfig = SpeechConfig2.fromHost(host, subscriptionKey);
706
+ }
707
+ } else {
708
+ speechConfig = authorizationToken ? SpeechConfig2.fromAuthorizationToken(authorizationToken, region) : SpeechConfig2.fromSubscription(subscriptionKey, region);
709
+ }
710
+ if (speechRecognitionEndpointId) {
711
+ speechConfig.endpointId = speechRecognitionEndpointId;
712
+ }
713
+ speechConfig.outputFormat = OutputFormat2.Detailed;
714
+ speechConfig.speechRecognitionLanguage = lang || "en-US";
715
+ return new SpeechRecognizer2(speechConfig, audioConfig);
716
+ };
717
+ return createSpeechRecognitionPonyfillFromRecognizer({
718
+ audioConfig,
719
+ createRecognizer,
720
+ enableTelemetry,
721
+ looseEvents,
722
+ referenceGrammars,
723
+ textNormalization
724
+ });
725
+ };
726
+
727
+ // src/SpeechServices/SpeechToText.js
728
+ var SpeechToText_default = createSpeechRecognitionPonyfill_default;
729
+
730
+ // src/SpeechServices/TextToSpeech/createSpeechSynthesisPonyfill.js
731
+ var import_event_target_shim4 = require("event-target-shim");
732
+ var import_on_error_resume_next = __toESM(require("on-error-resume-next"));
733
+
734
+ // src/SpeechServices/TextToSpeech/AudioContextQueue.js
735
+ var import_memoize_one = __toESM(require("memoize-one"));
736
+
737
+ // src/SpeechServices/TextToSpeech/AudioContextConsumer.js
738
+ var AudioContextConsumer_default = class {
739
+ constructor(audioContext) {
740
+ this.audioContext = audioContext;
741
+ }
742
+ pause() {
743
+ this.audioContext && this.audioContext.suspend();
744
+ this.playingUtterance && this.playingUtterance.dispatchEvent(new CustomEvent("pause"));
745
+ }
746
+ resume() {
747
+ this.audioContext && this.audioContext.resume();
748
+ this.playingUtterance && this.playingUtterance.dispatchEvent(new CustomEvent("resume"));
749
+ }
750
+ async start(queue) {
751
+ let utterance;
752
+ while (utterance = queue.shift()) {
753
+ this.playingUtterance = utterance;
754
+ await utterance.play(this.audioContext);
755
+ this.playingUtterance = null;
756
+ }
757
+ }
758
+ stop() {
759
+ this.playingUtterance && this.playingUtterance.stop();
760
+ if (this.audioContext.state === "suspended") {
761
+ this.audioContext.resume();
762
+ }
763
+ }
764
+ };
765
+
766
+ // src/SpeechServices/TextToSpeech/AudioContextQueue.js
767
+ var AudioContextQueue_default = class {
768
+ constructor({ audioContext, ponyfill }) {
769
+ this.consumer = null;
770
+ this.paused = false;
771
+ this.queue = [];
772
+ this.getAudioContext = (0, import_memoize_one.default)(() => audioContext || new ponyfill.AudioContext());
773
+ }
774
+ pause() {
775
+ this.paused = true;
776
+ this.consumer && this.consumer.pause();
777
+ }
778
+ push(utterance) {
779
+ this.queue.push(utterance);
780
+ this.startConsumer();
781
+ }
782
+ resume() {
783
+ this.paused = false;
784
+ if (this.consumer) {
785
+ this.consumer.resume();
786
+ } else {
787
+ this.startConsumer();
788
+ }
789
+ }
790
+ get speaking() {
791
+ return !!this.consumer;
792
+ }
793
+ async startConsumer() {
794
+ while (!this.paused && this.queue.length && !this.consumer) {
795
+ this.consumer = new AudioContextConsumer_default(this.getAudioContext());
796
+ await this.consumer.start(this.queue);
797
+ this.consumer = null;
798
+ }
799
+ }
800
+ stop() {
801
+ this.queue.splice(0);
802
+ this.consumer && this.consumer.stop();
803
+ }
804
+ };
805
+
806
+ // src/SpeechServices/TextToSpeech/SpeechSynthesisVoice.js
807
+ var SpeechSynthesisVoice_default = class {
808
+ constructor({ gender, lang, voiceURI }) {
809
+ this._default = false;
810
+ this._gender = gender;
811
+ this._lang = lang;
812
+ this._localService = false;
813
+ this._name = voiceURI;
814
+ this._voiceURI = voiceURI;
815
+ }
816
+ get default() {
817
+ return this._default;
818
+ }
819
+ get gender() {
820
+ return this._gender;
821
+ }
822
+ get lang() {
823
+ return this._lang;
824
+ }
825
+ get localService() {
826
+ return this._localService;
827
+ }
828
+ get name() {
829
+ return this._name;
830
+ }
831
+ get voiceURI() {
832
+ return this._voiceURI;
833
+ }
834
+ };
835
+
836
+ // src/SpeechServices/TextToSpeech/fetchCustomVoices.js
837
+ async function fetchCustomVoices({ customVoiceHostname, deploymentId, region, subscriptionKey }) {
838
+ const hostname = customVoiceHostname || `${region}.customvoice.api.speech.microsoft.com`;
839
+ const res = await fetch(
840
+ `https://${encodeURI(hostname)}/api/texttospeech/v2.0/endpoints/${encodeURIComponent(deploymentId)}`,
841
+ {
842
+ headers: {
843
+ accept: "application/json",
844
+ "ocp-apim-subscription-key": subscriptionKey
845
+ }
846
+ }
847
+ );
848
+ if (!res.ok) {
849
+ throw new Error("Failed to fetch custom voices");
850
+ }
851
+ return res.json();
852
+ }
853
+ async function fetchCustomVoices_default({ customVoiceHostname, deploymentId, region, subscriptionKey }) {
854
+ const { models } = await fetchCustomVoices({ customVoiceHostname, deploymentId, region, subscriptionKey });
855
+ return models.map(
856
+ ({ properties: { Gender: gender }, locale: lang, name: voiceURI }) => new SpeechSynthesisVoice_default({ gender, lang, voiceURI })
857
+ ).sort(({ name: x }, { name: y }) => x > y ? 1 : x < y ? -1 : 0);
858
+ }
859
+
860
+ // src/SpeechServices/TextToSpeech/fetchVoices.js
861
+ async function fetchVoices({ authorizationToken, region, speechSynthesisHostname, subscriptionKey }) {
862
+ const hostname = speechSynthesisHostname || `${encodeURI(region)}.tts.speech.microsoft.com`;
863
+ const res = await fetch(`https://${hostname}/cognitiveservices/voices/list`, {
864
+ headers: {
865
+ "content-type": "application/json",
866
+ ...authorizationToken ? {
867
+ authorization: `Bearer ${authorizationToken}`
868
+ } : {
869
+ "Ocp-Apim-Subscription-Key": subscriptionKey
870
+ }
871
+ }
872
+ });
873
+ if (!res.ok) {
874
+ throw new Error("Failed to fetch voices");
875
+ }
876
+ const voices = await res.json();
877
+ return voices.map(({ Gender: gender, Locale: lang, Name: voiceURI }) => new SpeechSynthesisVoice_default({ gender, lang, voiceURI })).sort(({ name: x }, { name: y }) => x > y ? 1 : x < y ? -1 : 0);
878
+ }
879
+
880
+ // src/SpeechServices/TextToSpeech/SpeechSynthesisEvent.js
881
+ var import_event_target_shim2 = require("event-target-shim");
882
+ var SpeechSynthesisEvent = class extends import_event_target_shim2.Event {
883
+ constructor(type) {
884
+ super(type);
885
+ }
886
+ };
887
+
888
+ // src/SpeechServices/TextToSpeech/SpeechSynthesisUtterance.js
889
+ var import_event_target_shim3 = require("event-target-shim");
890
+ var import_event_as_promise = __toESM(require("event-as-promise"));
891
+
892
+ // src/SpeechServices/TextToSpeech/fetchSpeechData.js
893
+ var import_base64_arraybuffer = require("base64-arraybuffer");
894
+
895
+ // src/SpeechServices/TextToSpeech/buildSSML.js
896
+ function relativePercentage(value) {
897
+ let relative = Math.round((value - 1) * 100);
898
+ if (relative >= 0) {
899
+ relative = "+" + relative;
900
+ }
901
+ return relative + "%";
902
+ }
903
+ function buildSSML({ lang, pitch = 1, rate = 1, text, voice, volume }) {
904
+ return `<speak version="1.0" xml:lang="${lang}">
905
+ <voice xml:lang="${lang}" name="${voice}">
906
+ <prosody pitch="${relativePercentage(pitch)}" rate="${relativePercentage(rate)}" volume="${relativePercentage(
907
+ volume
908
+ )}">
909
+ ${text}
910
+ </prosody>
911
+ </voice>
912
+ </speak>`;
913
+ }
914
+
915
+ // src/SpeechServices/TextToSpeech/isSSML.js
916
+ var SPEAK_TAG_PATTERN = /^\s*<speak(\s|\/?>)/u;
917
+ var XML_PROLOG_PATTERN = /^\s*<\?xml\s/u;
918
+ function isSSML(text) {
919
+ return SPEAK_TAG_PATTERN.test(text) || XML_PROLOG_PATTERN.test(text);
920
+ }
921
+
922
+ // src/SpeechServices/TextToSpeech/fetchSpeechData.js
923
+ var DEFAULT_LANGUAGE = "en-US";
924
+ var DEFAULT_OUTPUT_FORMAT = "riff-16khz-16bit-mono-pcm";
925
+ var DEFAULT_VOICE = "Microsoft Server Speech Text to Speech Voice (en-US, AriaNeural)";
926
+ var EMPTY_MP3_BASE64 = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjU2LjEwMQAAAAAAAAAAAAAA//tAwAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAACAAABhgC7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3LjY0AAAAAAAAAAAAAAAAJAUHAAAAAAAAAYYoRBqpAAAAAAD/+xDEAAPAAAGkAAAAIAAANIAAAARMQU1FMy45OS41VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EMQpg8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV";
927
+ async function fetchSpeechData_default({
928
+ deploymentId,
929
+ fetchCredentials,
930
+ lang = DEFAULT_LANGUAGE,
931
+ outputFormat = DEFAULT_OUTPUT_FORMAT,
932
+ pitch,
933
+ rate,
934
+ text,
935
+ voice = DEFAULT_VOICE,
936
+ volume
937
+ }) {
938
+ if (!text) {
939
+ return (0, import_base64_arraybuffer.decode)(EMPTY_MP3_BASE64);
940
+ }
941
+ const { authorizationToken, region, speechSynthesisHostname, subscriptionKey } = await fetchCredentials();
942
+ if (authorizationToken && subscriptionKey || !authorizationToken && !subscriptionKey) {
943
+ throw new Error('Only "authorizationToken" or "subscriptionKey" should be set.');
944
+ } else if (region && speechSynthesisHostname || !region && !speechSynthesisHostname) {
945
+ throw new Error('Only "region" or "speechSynthesisHostnamename" should be set.');
946
+ }
947
+ const ssml = isSSML(text) ? text : buildSSML({ lang, pitch, rate, text, voice, volume });
948
+ const hostname = speechSynthesisHostname || (deploymentId ? `${encodeURI(region)}.voice.speech.microsoft.com` : `${encodeURI(region)}.tts.speech.microsoft.com`);
949
+ const search = deploymentId ? `?deploymentId=${encodeURI(deploymentId)}` : "";
950
+ const url = `https://${hostname}/cognitiveservices/v1${search}`;
951
+ const res = await fetch(url, {
952
+ headers: {
953
+ "Content-Type": "application/ssml+xml",
954
+ "X-Microsoft-OutputFormat": outputFormat,
955
+ ...authorizationToken ? {
956
+ Authorization: `Bearer ${authorizationToken}`
957
+ } : {
958
+ "Ocp-Apim-Subscription-Key": subscriptionKey
959
+ }
960
+ },
961
+ method: "POST",
962
+ body: ssml
963
+ });
964
+ if (!res.ok) {
965
+ throw new Error(`web-speech-cognitive-services: Failed to syntheis speech, server returned ${res.status}`);
966
+ }
967
+ return res.arrayBuffer();
968
+ }
969
+
970
+ // src/SpeechServices/TextToSpeech/subscribeEvent.js
971
+ function subscribeEvent(target, name, handler) {
972
+ target.addEventListener(name, handler);
973
+ return () => target.removeEventListener(name, handler);
974
+ }
975
+
976
+ // src/SpeechServices/TextToSpeech/SpeechSynthesisUtterance.js
977
+ function asyncDecodeAudioData(audioContext, arrayBuffer) {
978
+ return new Promise((resolve, reject) => {
979
+ const promise = audioContext.decodeAudioData(arrayBuffer, resolve, reject);
980
+ promise && typeof promise.then === "function" && resolve(promise);
981
+ });
982
+ }
983
+ function playDecoded(audioContext, audioBuffer, source) {
984
+ return new Promise((resolve, reject) => {
985
+ const audioContextClosed = new import_event_as_promise.default();
986
+ const sourceEnded = new import_event_as_promise.default();
987
+ const unsubscribe = subscribeEvent(
988
+ audioContext,
989
+ "statechange",
990
+ ({ target: { state } }) => state === "closed" && audioContextClosed.eventListener()
991
+ );
992
+ try {
993
+ source.buffer = audioBuffer;
994
+ source.onended = sourceEnded.eventListener;
995
+ source.connect(audioContext.destination);
996
+ source.start(0);
997
+ Promise.race([audioContextClosed.upcoming(), sourceEnded.upcoming()]).then(resolve);
998
+ } catch (err) {
999
+ reject(err);
1000
+ } finally {
1001
+ unsubscribe();
1002
+ }
1003
+ });
1004
+ }
1005
+ var SpeechSynthesisUtterance = class extends import_event_target_shim3.EventTarget {
1006
+ constructor(text) {
1007
+ super();
1008
+ this._lang = null;
1009
+ this._pitch = 1;
1010
+ this._rate = 1;
1011
+ this._voice = null;
1012
+ this._volume = 1;
1013
+ this.text = text;
1014
+ this.onboundary = null;
1015
+ this.onend = null;
1016
+ this.onerror = null;
1017
+ this.onmark = null;
1018
+ this.onpause = null;
1019
+ this.onresume = null;
1020
+ this.onstart = null;
1021
+ }
1022
+ get lang() {
1023
+ return this._lang;
1024
+ }
1025
+ set lang(value) {
1026
+ this._lang = value;
1027
+ }
1028
+ get onboundary() {
1029
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "boundary");
1030
+ }
1031
+ set onboundary(value) {
1032
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "boundary", value);
1033
+ }
1034
+ get onend() {
1035
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "end");
1036
+ }
1037
+ set onend(value) {
1038
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "end", value);
1039
+ }
1040
+ get onerror() {
1041
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "error");
1042
+ }
1043
+ set onerror(value) {
1044
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "error", value);
1045
+ }
1046
+ get onmark() {
1047
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "mark");
1048
+ }
1049
+ set onmark(value) {
1050
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "mark", value);
1051
+ }
1052
+ get onpause() {
1053
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "pause");
1054
+ }
1055
+ set onpause(value) {
1056
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "pause", value);
1057
+ }
1058
+ get onresume() {
1059
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "resume");
1060
+ }
1061
+ set onresume(value) {
1062
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "resume", value);
1063
+ }
1064
+ get onstart() {
1065
+ return (0, import_event_target_shim3.getEventAttributeValue)(this, "start");
1066
+ }
1067
+ set onstart(value) {
1068
+ (0, import_event_target_shim3.setEventAttributeValue)(this, "start", value);
1069
+ }
1070
+ get pitch() {
1071
+ return this._pitch;
1072
+ }
1073
+ set pitch(value) {
1074
+ this._pitch = value;
1075
+ }
1076
+ get rate() {
1077
+ return this._rate;
1078
+ }
1079
+ set rate(value) {
1080
+ this._rate = value;
1081
+ }
1082
+ get voice() {
1083
+ return this._voice;
1084
+ }
1085
+ set voice(value) {
1086
+ this._voice = value;
1087
+ }
1088
+ get volume() {
1089
+ return this._volume;
1090
+ }
1091
+ set volume(value) {
1092
+ this._volume = value;
1093
+ }
1094
+ preload({ deploymentId, fetchCredentials, outputFormat }) {
1095
+ this.arrayBufferPromise = fetchSpeechData_default({
1096
+ fetchCredentials,
1097
+ deploymentId,
1098
+ lang: this.lang || window.navigator.language,
1099
+ outputFormat,
1100
+ pitch: this.pitch,
1101
+ rate: this.rate,
1102
+ text: this.text,
1103
+ voice: this.voice && this.voice.voiceURI,
1104
+ volume: this.volume
1105
+ });
1106
+ this.arrayBufferPromise.catch();
1107
+ }
1108
+ async play(audioContext) {
1109
+ try {
1110
+ this.dispatchEvent(new SpeechSynthesisEvent("start"));
1111
+ const source = audioContext.createBufferSource();
1112
+ const audioBuffer = await asyncDecodeAudioData(audioContext, await this.arrayBufferPromise);
1113
+ this._playingSource = source;
1114
+ await playDecoded(audioContext, audioBuffer, source);
1115
+ this._playingSource = null;
1116
+ this.dispatchEvent(new SpeechSynthesisEvent("end"));
1117
+ } catch (error) {
1118
+ this.dispatchEvent(new ErrorEvent("error", { error: "synthesis-failed", message: error.stack }));
1119
+ }
1120
+ }
1121
+ stop() {
1122
+ this._playingSource && this._playingSource.stop();
1123
+ }
1124
+ };
1125
+ var SpeechSynthesisUtterance_default = SpeechSynthesisUtterance;
1126
+
1127
+ // src/SpeechServices/TextToSpeech/createSpeechSynthesisPonyfill.js
1128
+ var DEFAULT_OUTPUT_FORMAT2 = "audio-24khz-160kbitrate-mono-mp3";
1129
+ var EMPTY_ARRAY = [];
1130
+ var createSpeechSynthesisPonyfill_default = (options) => {
1131
+ const {
1132
+ audioContext,
1133
+ fetchCredentials,
1134
+ ponyfill = {
1135
+ AudioContext: window.AudioContext || window.webkitAudioContext
1136
+ },
1137
+ speechSynthesisDeploymentId,
1138
+ speechSynthesisOutputFormat = DEFAULT_OUTPUT_FORMAT2
1139
+ } = patchOptions(options);
1140
+ if (!audioContext && !ponyfill.AudioContext) {
1141
+ console.warn(
1142
+ "web-speech-cognitive-services: This browser does not support Web Audio and it will not work with Cognitive Services Speech Services."
1143
+ );
1144
+ return {};
1145
+ }
1146
+ class SpeechSynthesis extends import_event_target_shim4.EventTarget {
1147
+ constructor() {
1148
+ super();
1149
+ this.queue = new AudioContextQueue_default({ audioContext, ponyfill });
1150
+ this.updateVoices();
1151
+ }
1152
+ cancel() {
1153
+ this.queue.stop();
1154
+ }
1155
+ getVoices() {
1156
+ return EMPTY_ARRAY;
1157
+ }
1158
+ get onvoiceschanged() {
1159
+ return (0, import_event_target_shim4.getEventAttributeValue)(this, "voiceschanged");
1160
+ }
1161
+ set onvoiceschanged(value) {
1162
+ (0, import_event_target_shim4.setEventAttributeValue)(this, "voiceschanged", value);
1163
+ }
1164
+ pause() {
1165
+ this.queue.pause();
1166
+ }
1167
+ resume() {
1168
+ this.queue.resume();
1169
+ }
1170
+ speak(utterance) {
1171
+ if (!(utterance instanceof SpeechSynthesisUtterance_default)) {
1172
+ throw new Error("invalid utterance");
1173
+ }
1174
+ const { reject, resolve, promise } = pDefer();
1175
+ const handleError = ({ error: errorCode, message }) => {
1176
+ const error = new Error(errorCode);
1177
+ error.stack = message;
1178
+ reject(error);
1179
+ };
1180
+ utterance.addEventListener("end", resolve);
1181
+ utterance.addEventListener("error", handleError);
1182
+ utterance.preload({
1183
+ deploymentId: speechSynthesisDeploymentId,
1184
+ fetchCredentials,
1185
+ outputFormat: speechSynthesisOutputFormat
1186
+ });
1187
+ this.queue.push(utterance);
1188
+ return promise.finally(() => {
1189
+ utterance.removeEventListener("end", resolve);
1190
+ utterance.removeEventListener("error", handleError);
1191
+ });
1192
+ }
1193
+ get speaking() {
1194
+ return this.queue.speaking;
1195
+ }
1196
+ async updateVoices() {
1197
+ const { customVoiceHostname, region, speechSynthesisHostname, subscriptionKey } = await fetchCredentials();
1198
+ if (speechSynthesisDeploymentId) {
1199
+ if (subscriptionKey) {
1200
+ console.warn(
1201
+ "web-speech-cognitive-services: Listing of custom voice models are only available when using subscription key."
1202
+ );
1203
+ await (0, import_on_error_resume_next.default)(async () => {
1204
+ const voices = await fetchCustomVoices_default({
1205
+ customVoiceHostname,
1206
+ deploymentId: speechSynthesisDeploymentId,
1207
+ region,
1208
+ speechSynthesisHostname,
1209
+ subscriptionKey
1210
+ });
1211
+ this.getVoices = () => voices;
1212
+ });
1213
+ }
1214
+ } else {
1215
+ await (0, import_on_error_resume_next.default)(async () => {
1216
+ const voices = await fetchVoices(await fetchCredentials());
1217
+ this.getVoices = () => voices;
1218
+ });
1219
+ }
1220
+ this.dispatchEvent(new SpeechSynthesisEvent("voiceschanged"));
1221
+ }
1222
+ }
1223
+ return {
1224
+ speechSynthesis: new SpeechSynthesis(),
1225
+ SpeechSynthesisEvent,
1226
+ SpeechSynthesisUtterance: SpeechSynthesisUtterance_default
1227
+ };
1228
+ };
1229
+
1230
+ // src/SpeechServices/TextToSpeech.js
1231
+ var TextToSpeech_default = createSpeechSynthesisPonyfill_default;
1232
+
1233
+ // src/SpeechServices/fetchAuthorizationToken.js
1234
+ var TOKEN_URL_TEMPLATE = "https://{region}.api.cognitive.microsoft.com/sts/v1.0/issueToken";
1235
+ async function fetchAuthorizationToken_default({ region, subscriptionKey }) {
1236
+ const res = await fetch(TOKEN_URL_TEMPLATE.replace(/\{region\}/u, region), {
1237
+ headers: {
1238
+ "Ocp-Apim-Subscription-Key": subscriptionKey
1239
+ },
1240
+ method: "POST"
1241
+ });
1242
+ if (!res.ok) {
1243
+ throw new Error(`Failed to fetch authorization token, server returned ${res.status}`);
1244
+ }
1245
+ return res.text();
1246
+ }
1247
+
1248
+ // src/SpeechServices.js
1249
+ function createSpeechServicesPonyfill(options = {}, ...args) {
1250
+ return {
1251
+ ...SpeechToText_default(options, ...args),
1252
+ ...TextToSpeech_default(options, ...args)
1253
+ };
1254
+ }
1255
+ var meta = document.createElement("meta");
1256
+ meta.setAttribute("name", "web-speech-cognitive-services");
1257
+ meta.setAttribute("content", `version=${"8.0.0-main.85313be"}`);
1258
+ document.head.appendChild(meta);
1259
+ // Annotate the CommonJS export names for ESM import in node:
1260
+ 0 && (module.exports = {
1261
+ createSpeechRecognitionPonyfill,
1262
+ createSpeechRecognitionPonyfillFromRecognizer,
1263
+ createSpeechServicesPonyfill,
1264
+ createSpeechSynthesisPonyfill,
1265
+ fetchAuthorizationToken
1266
+ });
1267
+ //# sourceMappingURL=web-speech-cognitive-services.js.map