rystem.playframework.client 0.1.2 → 0.1.4
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.
- package/README.md +380 -1666
- package/lib/engine/PlayFrameworkClient.d.ts +19 -0
- package/lib/engine/PlayFrameworkClient.d.ts.map +1 -1
- package/lib/engine/PlayFrameworkClient.js +95 -7
- package/lib/index.d.ts +9 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +9 -1
- package/lib/models/PlayFrameworkRequest.d.ts +10 -0
- package/lib/models/PlayFrameworkRequest.d.ts.map +1 -1
- package/lib/models/VoiceResponse.d.ts +39 -0
- package/lib/models/VoiceResponse.d.ts.map +1 -0
- package/lib/models/VoiceResponse.js +2 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts +128 -0
- package/lib/utils/BrowserSpeechRecognizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechRecognizer.js +150 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts +148 -0
- package/lib/utils/BrowserSpeechSynthesizer.d.ts.map +1 -0
- package/lib/utils/BrowserSpeechSynthesizer.js +400 -0
- package/lib/utils/BrowserVoiceClient.d.ts +142 -0
- package/lib/utils/BrowserVoiceClient.d.ts.map +1 -0
- package/lib/utils/BrowserVoiceClient.js +200 -0
- package/lib/utils/VoiceRecorder.d.ts +90 -0
- package/lib/utils/VoiceRecorder.d.ts.map +1 -0
- package/lib/utils/VoiceRecorder.js +195 -0
- package/package.json +1 -1
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for BrowserSpeechSynthesizer.
|
|
3
|
+
*/
|
|
4
|
+
export interface BrowserSpeechSynthesizerOptions {
|
|
5
|
+
/** BCP-47 language code (e.g. 'it-IT', 'en-US'). Default: browser default. */
|
|
6
|
+
lang?: string;
|
|
7
|
+
/** Speech rate (0.1 - 10). Default: `1`. */
|
|
8
|
+
rate?: number;
|
|
9
|
+
/** Pitch (0 - 2). Default: `1`. */
|
|
10
|
+
pitch?: number;
|
|
11
|
+
/** Volume (0 - 1). Default: `1`. */
|
|
12
|
+
volume?: number;
|
|
13
|
+
/** Preferred voice name (e.g. 'Google italiano'). If not found, uses first matching lang voice. */
|
|
14
|
+
voiceName?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Sentence delimiters used to split streaming text into speakable chunks.
|
|
17
|
+
* Default: `['.', '!', '?', '\n']`.
|
|
18
|
+
*/
|
|
19
|
+
sentenceDelimiters?: string[];
|
|
20
|
+
/**
|
|
21
|
+
* Minimum character count before flushing a sentence for speech.
|
|
22
|
+
* Prevents speaking very short fragments. Default: `20`.
|
|
23
|
+
*/
|
|
24
|
+
minCharsBeforeSpeak?: number;
|
|
25
|
+
/**
|
|
26
|
+
* When `true`, prefer browser-local voices (no network round-trip) over
|
|
27
|
+
* cloud/remote voices. Local voices synthesize instantly, eliminating
|
|
28
|
+
* the audible gap between sentences caused by network latency.
|
|
29
|
+
* Default: `true`.
|
|
30
|
+
*/
|
|
31
|
+
preferLocalVoice?: boolean;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Callbacks emitted by BrowserSpeechSynthesizer.
|
|
35
|
+
*/
|
|
36
|
+
export interface BrowserSpeechSynthesizerCallbacks {
|
|
37
|
+
/** Called when a sentence starts being spoken. */
|
|
38
|
+
onSpeakStart?: (text: string) => void;
|
|
39
|
+
/** Called when a sentence finishes being spoken. */
|
|
40
|
+
onSpeakEnd?: (text: string) => void;
|
|
41
|
+
/** Called when all queued speech has been spoken. */
|
|
42
|
+
onQueueEmpty?: () => void;
|
|
43
|
+
/** Called on speech error. */
|
|
44
|
+
onError?: (error: Error) => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Wraps the browser Web Speech API `SpeechSynthesis` for text-to-speech,
|
|
48
|
+
* with built-in sentence accumulation for streaming scenarios.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* const synth = new BrowserSpeechSynthesizer({ lang: 'it-IT', rate: 1.1 });
|
|
53
|
+
*
|
|
54
|
+
* // Simple usage
|
|
55
|
+
* await synth.speak("Ciao, come stai?");
|
|
56
|
+
*
|
|
57
|
+
* // Streaming usage — feed text chunks as they arrive
|
|
58
|
+
* synth.feedChunk("Ciao, ");
|
|
59
|
+
* synth.feedChunk("come stai? ");
|
|
60
|
+
* synth.feedChunk("Tutto bene.");
|
|
61
|
+
* synth.flush(); // speak any remaining text
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare class BrowserSpeechSynthesizer {
|
|
65
|
+
private options;
|
|
66
|
+
private callbacks;
|
|
67
|
+
private buffer;
|
|
68
|
+
private _isSpeaking;
|
|
69
|
+
/** Number of utterances currently in the browser's native speech queue. */
|
|
70
|
+
private _pendingCount;
|
|
71
|
+
private resolvedVoice;
|
|
72
|
+
private voiceResolved;
|
|
73
|
+
private warmedUp;
|
|
74
|
+
/** Chrome keepalive: periodic pause/resume to prevent auto-pause after ~15s. */
|
|
75
|
+
private keepAliveTimer;
|
|
76
|
+
constructor(options?: BrowserSpeechSynthesizerOptions, callbacks?: BrowserSpeechSynthesizerCallbacks);
|
|
77
|
+
/** Whether speech is currently being synthesized. */
|
|
78
|
+
get isSpeaking(): boolean;
|
|
79
|
+
/** Returns `true` if the browser supports the Web Speech Synthesis API. */
|
|
80
|
+
static isSupported(): boolean;
|
|
81
|
+
/** Set event callbacks. */
|
|
82
|
+
setCallbacks(callbacks: BrowserSpeechSynthesizerCallbacks): void;
|
|
83
|
+
/** Update language at runtime. Resets the resolved voice cache. */
|
|
84
|
+
setLang(lang: string): void;
|
|
85
|
+
/**
|
|
86
|
+
* Get available voices. Due to browser async loading, you may need to call this
|
|
87
|
+
* after the `voiceschanged` event fires, or retry after a short delay.
|
|
88
|
+
*/
|
|
89
|
+
static getVoices(): SpeechSynthesisVoice[];
|
|
90
|
+
/**
|
|
91
|
+
* Speak a complete text. Returns a Promise that resolves when the utterance finishes.
|
|
92
|
+
*/
|
|
93
|
+
speak(text: string): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Feed a streaming text chunk. Text is accumulated until a sentence boundary is found,
|
|
96
|
+
* then the complete sentence is queued for speaking.
|
|
97
|
+
*/
|
|
98
|
+
feedChunk(chunk: string): void;
|
|
99
|
+
/**
|
|
100
|
+
* Flush any remaining buffered text (e.g. at end of stream) and queue it for speaking.
|
|
101
|
+
*/
|
|
102
|
+
flush(): void;
|
|
103
|
+
/**
|
|
104
|
+
* Flush and wait for all queued sentences to finish speaking.
|
|
105
|
+
* Returns a Promise that resolves when the queue is empty and speech is done.
|
|
106
|
+
*/
|
|
107
|
+
flushAndWait(): Promise<void>;
|
|
108
|
+
/** Cancel all speech and clear the queue. */
|
|
109
|
+
cancel(): void;
|
|
110
|
+
/**
|
|
111
|
+
* Pre-warm Chrome's TTS engine by speaking a zero-volume silent utterance.
|
|
112
|
+
* This primes the internal synthesis pipeline (voice loading, audio context
|
|
113
|
+
* creation, etc.) so that the first real utterance starts faster.
|
|
114
|
+
*/
|
|
115
|
+
private preWarm;
|
|
116
|
+
/** Pause speech. */
|
|
117
|
+
pause(): void;
|
|
118
|
+
/** Resume speech. */
|
|
119
|
+
resume(): void;
|
|
120
|
+
private extractAndQueueSentences;
|
|
121
|
+
/**
|
|
122
|
+
* Submit a sentence directly to the browser's native speech queue.
|
|
123
|
+
* The browser pre-processes queued utterances so the next one starts
|
|
124
|
+
* immediately when the current one finishes — no gap between sentences.
|
|
125
|
+
*/
|
|
126
|
+
private enqueue;
|
|
127
|
+
private createUtterance;
|
|
128
|
+
/**
|
|
129
|
+
* Normalize a BCP-47 lang code: lowercase and replace underscores with hyphens.
|
|
130
|
+
*/
|
|
131
|
+
private static normalizeLang;
|
|
132
|
+
private resolveVoice;
|
|
133
|
+
/**
|
|
134
|
+
* Chrome workaround: keeps speech synthesis alive.
|
|
135
|
+
* Chrome auto-pauses `speechSynthesis` after ~15 seconds of continuous speech.
|
|
136
|
+
* Calling `pause()` then `resume()` periodically resets this internal timer.
|
|
137
|
+
*/
|
|
138
|
+
private startKeepAlive;
|
|
139
|
+
/** Stop the Chrome keepalive timer. */
|
|
140
|
+
private stopKeepAlive;
|
|
141
|
+
/**
|
|
142
|
+
* Strip common Markdown formatting so TTS reads only the plain text.
|
|
143
|
+
* Handles: bold, italic, strikethrough, inline code, code blocks,
|
|
144
|
+
* headers, links, images, blockquotes, list markers, horizontal rules.
|
|
145
|
+
*/
|
|
146
|
+
static stripMarkdown(text: string): string;
|
|
147
|
+
}
|
|
148
|
+
//# sourceMappingURL=BrowserSpeechSynthesizer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BrowserSpeechSynthesizer.d.ts","sourceRoot":"","sources":["../../src/utils/BrowserSpeechSynthesizer.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,+BAA+B;IAC5C,8EAA8E;IAC9E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,4CAA4C;IAC5C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mCAAmC;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oCAAoC;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mGAAmG;IACnG,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED;;GAEG;AACH,MAAM,WAAW,iCAAiC;IAC9C,kDAAkD;IAClD,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACtC,oDAAoD;IACpD,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IACpC,qDAAqD;IACrD,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,8BAA8B;IAC9B,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CACpC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,wBAAwB;IACjC,OAAO,CAAC,OAAO,CAA4C;IAC3D,OAAO,CAAC,SAAS,CAAyC;IAC1D,OAAO,CAAC,MAAM,CAAM;IACpB,OAAO,CAAC,WAAW,CAAS;IAC5B,2EAA2E;IAC3E,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,aAAa,CAAqC;IAC1D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAS;IACzB,gFAAgF;IAChF,OAAO,CAAC,cAAc,CAA+C;gBAEzD,OAAO,CAAC,EAAE,+BAA+B,EAAE,SAAS,CAAC,EAAE,iCAAiC;IA4BpG,qDAAqD;IACrD,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,2EAA2E;IAC3E,MAAM,CAAC,WAAW,IAAI,OAAO;IAI7B,2BAA2B;IAC3B,YAAY,CAAC,SAAS,EAAE,iCAAiC,GAAG,IAAI;IAIhE,mEAAmE;IACnE,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAM3B;;;OAGG;IACH,MAAM,CAAC,SAAS,IAAI,oBAAoB,EAAE;IAM1C;;OAEG;IACH,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA2ClC;;;OAGG;IACH,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAU9B;;OAEG;IACH,KAAK,IAAI,IAAI;IAQb;;;OAGG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBnC,6CAA6C;IAC7C,MAAM,IAAI,IAAI;IASd;;;;OAIG;IACH,OAAO,CAAC,OAAO;IAiBf,oBAAoB;IACpB,KAAK,IAAI,IAAI;IAIb,qBAAqB;IACrB,MAAM,IAAI,IAAI;IAMd,OAAO,CAAC,wBAAwB;IAqBhC;;;;OAIG;IACH,OAAO,CAAC,OAAO;IA6Cf,OAAO,CAAC,eAAe;IAqBvB;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,aAAa;IAI5B,OAAO,CAAC,YAAY;IAyDpB;;;;OAIG;IACH,OAAO,CAAC,cAAc;IAUtB,uCAAuC;IACvC,OAAO,CAAC,aAAa;IAOrB;;;;OAIG;IACH,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAkC7C"}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BrowserSpeechSynthesizer = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Wraps the browser Web Speech API `SpeechSynthesis` for text-to-speech,
|
|
6
|
+
* with built-in sentence accumulation for streaming scenarios.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const synth = new BrowserSpeechSynthesizer({ lang: 'it-IT', rate: 1.1 });
|
|
11
|
+
*
|
|
12
|
+
* // Simple usage
|
|
13
|
+
* await synth.speak("Ciao, come stai?");
|
|
14
|
+
*
|
|
15
|
+
* // Streaming usage — feed text chunks as they arrive
|
|
16
|
+
* synth.feedChunk("Ciao, ");
|
|
17
|
+
* synth.feedChunk("come stai? ");
|
|
18
|
+
* synth.feedChunk("Tutto bene.");
|
|
19
|
+
* synth.flush(); // speak any remaining text
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
class BrowserSpeechSynthesizer {
|
|
23
|
+
options;
|
|
24
|
+
callbacks = {};
|
|
25
|
+
buffer = '';
|
|
26
|
+
_isSpeaking = false;
|
|
27
|
+
/** Number of utterances currently in the browser's native speech queue. */
|
|
28
|
+
_pendingCount = 0;
|
|
29
|
+
resolvedVoice = null;
|
|
30
|
+
voiceResolved = false;
|
|
31
|
+
warmedUp = false;
|
|
32
|
+
/** Chrome keepalive: periodic pause/resume to prevent auto-pause after ~15s. */
|
|
33
|
+
keepAliveTimer = null;
|
|
34
|
+
constructor(options, callbacks) {
|
|
35
|
+
this.options = {
|
|
36
|
+
lang: options?.lang ?? '',
|
|
37
|
+
rate: options?.rate ?? 1,
|
|
38
|
+
pitch: options?.pitch ?? 1,
|
|
39
|
+
volume: options?.volume ?? 1,
|
|
40
|
+
voiceName: options?.voiceName ?? '',
|
|
41
|
+
sentenceDelimiters: options?.sentenceDelimiters ?? ['.', '!', '?', '\n'],
|
|
42
|
+
minCharsBeforeSpeak: options?.minCharsBeforeSpeak ?? 20,
|
|
43
|
+
preferLocalVoice: options?.preferLocalVoice ?? true,
|
|
44
|
+
};
|
|
45
|
+
if (callbacks)
|
|
46
|
+
this.callbacks = callbacks;
|
|
47
|
+
// Pre-load voices (Chrome loads them asynchronously)
|
|
48
|
+
if (BrowserSpeechSynthesizer.isSupported()) {
|
|
49
|
+
window.speechSynthesis.getVoices(); // trigger async load
|
|
50
|
+
window.speechSynthesis.addEventListener?.('voiceschanged', () => {
|
|
51
|
+
// Only re-resolve if we haven't successfully found a voice yet.
|
|
52
|
+
// Chrome fires this event multiple times as network voices load
|
|
53
|
+
// incrementally; if we already have a match, keep it stable to
|
|
54
|
+
// avoid language flipping mid-stream.
|
|
55
|
+
if (!this.resolvedVoice) {
|
|
56
|
+
this.voiceResolved = false;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Whether speech is currently being synthesized. */
|
|
62
|
+
get isSpeaking() {
|
|
63
|
+
return this._isSpeaking;
|
|
64
|
+
}
|
|
65
|
+
/** Returns `true` if the browser supports the Web Speech Synthesis API. */
|
|
66
|
+
static isSupported() {
|
|
67
|
+
return typeof window !== 'undefined' && 'speechSynthesis' in window;
|
|
68
|
+
}
|
|
69
|
+
/** Set event callbacks. */
|
|
70
|
+
setCallbacks(callbacks) {
|
|
71
|
+
this.callbacks = callbacks;
|
|
72
|
+
}
|
|
73
|
+
/** Update language at runtime. Resets the resolved voice cache. */
|
|
74
|
+
setLang(lang) {
|
|
75
|
+
this.options.lang = lang;
|
|
76
|
+
this.voiceResolved = false;
|
|
77
|
+
this.resolvedVoice = null;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Get available voices. Due to browser async loading, you may need to call this
|
|
81
|
+
* after the `voiceschanged` event fires, or retry after a short delay.
|
|
82
|
+
*/
|
|
83
|
+
static getVoices() {
|
|
84
|
+
return typeof window !== 'undefined' && 'speechSynthesis' in window
|
|
85
|
+
? window.speechSynthesis.getVoices()
|
|
86
|
+
: [];
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Speak a complete text. Returns a Promise that resolves when the utterance finishes.
|
|
90
|
+
*/
|
|
91
|
+
speak(text) {
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
if (!BrowserSpeechSynthesizer.isSupported()) {
|
|
94
|
+
reject(new Error('SpeechSynthesis API is not supported in this browser.'));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const trimmed = text.trim();
|
|
98
|
+
if (!trimmed) {
|
|
99
|
+
resolve();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
// Chrome workaround: cancel any stale/paused state before first speak
|
|
103
|
+
if (!this.warmedUp) {
|
|
104
|
+
window.speechSynthesis.cancel();
|
|
105
|
+
this.warmedUp = true;
|
|
106
|
+
}
|
|
107
|
+
const utterance = this.createUtterance(trimmed);
|
|
108
|
+
utterance.onstart = () => {
|
|
109
|
+
this._isSpeaking = true;
|
|
110
|
+
this.callbacks.onSpeakStart?.(trimmed);
|
|
111
|
+
};
|
|
112
|
+
utterance.onend = () => {
|
|
113
|
+
this._isSpeaking = false;
|
|
114
|
+
this.callbacks.onSpeakEnd?.(trimmed);
|
|
115
|
+
resolve();
|
|
116
|
+
};
|
|
117
|
+
utterance.onerror = (event) => {
|
|
118
|
+
this._isSpeaking = false;
|
|
119
|
+
const err = new Error(`SpeechSynthesis error: ${event.error}`);
|
|
120
|
+
this.callbacks.onError?.(err);
|
|
121
|
+
reject(err);
|
|
122
|
+
};
|
|
123
|
+
window.speechSynthesis.speak(utterance);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Feed a streaming text chunk. Text is accumulated until a sentence boundary is found,
|
|
128
|
+
* then the complete sentence is queued for speaking.
|
|
129
|
+
*/
|
|
130
|
+
feedChunk(chunk) {
|
|
131
|
+
// Pre-warm the TTS engine on the very first chunk so Chrome's internal
|
|
132
|
+
// pipeline is already initialised by the time the first real sentence is ready.
|
|
133
|
+
if (!this.warmedUp) {
|
|
134
|
+
this.preWarm();
|
|
135
|
+
}
|
|
136
|
+
this.buffer += chunk;
|
|
137
|
+
this.extractAndQueueSentences();
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Flush any remaining buffered text (e.g. at end of stream) and queue it for speaking.
|
|
141
|
+
*/
|
|
142
|
+
flush() {
|
|
143
|
+
const remaining = this.buffer.trim();
|
|
144
|
+
if (remaining) {
|
|
145
|
+
this.buffer = '';
|
|
146
|
+
this.enqueue(remaining);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Flush and wait for all queued sentences to finish speaking.
|
|
151
|
+
* Returns a Promise that resolves when the queue is empty and speech is done.
|
|
152
|
+
*/
|
|
153
|
+
async flushAndWait() {
|
|
154
|
+
this.flush();
|
|
155
|
+
if (this._pendingCount <= 0 && !this._isSpeaking)
|
|
156
|
+
return;
|
|
157
|
+
return new Promise((resolve) => {
|
|
158
|
+
const check = () => {
|
|
159
|
+
if (this._pendingCount <= 0 && !this._isSpeaking) {
|
|
160
|
+
resolve();
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
setTimeout(check, 100);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
check();
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/** Cancel all speech and clear the queue. */
|
|
170
|
+
cancel() {
|
|
171
|
+
this.stopKeepAlive();
|
|
172
|
+
window.speechSynthesis.cancel();
|
|
173
|
+
this.buffer = '';
|
|
174
|
+
this._isSpeaking = false;
|
|
175
|
+
this._pendingCount = 0;
|
|
176
|
+
this.warmedUp = false; // reset so next speak/feedChunk re-warms
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Pre-warm Chrome's TTS engine by speaking a zero-volume silent utterance.
|
|
180
|
+
* This primes the internal synthesis pipeline (voice loading, audio context
|
|
181
|
+
* creation, etc.) so that the first real utterance starts faster.
|
|
182
|
+
*/
|
|
183
|
+
preWarm() {
|
|
184
|
+
if (this.warmedUp || !BrowserSpeechSynthesizer.isSupported())
|
|
185
|
+
return;
|
|
186
|
+
window.speechSynthesis.cancel(); // clear any stale state
|
|
187
|
+
const utterance = new SpeechSynthesisUtterance('');
|
|
188
|
+
utterance.volume = 0;
|
|
189
|
+
// Resolve and assign the voice now so the engine pre-loads it
|
|
190
|
+
const voice = this.resolveVoice();
|
|
191
|
+
if (voice) {
|
|
192
|
+
utterance.voice = voice;
|
|
193
|
+
utterance.lang = voice.lang;
|
|
194
|
+
}
|
|
195
|
+
else if (this.options.lang) {
|
|
196
|
+
utterance.lang = this.options.lang;
|
|
197
|
+
}
|
|
198
|
+
window.speechSynthesis.speak(utterance);
|
|
199
|
+
this.warmedUp = true;
|
|
200
|
+
}
|
|
201
|
+
/** Pause speech. */
|
|
202
|
+
pause() {
|
|
203
|
+
window.speechSynthesis.pause();
|
|
204
|
+
}
|
|
205
|
+
/** Resume speech. */
|
|
206
|
+
resume() {
|
|
207
|
+
window.speechSynthesis.resume();
|
|
208
|
+
}
|
|
209
|
+
// ── Private ────────────────────────────────────────────────
|
|
210
|
+
extractAndQueueSentences() {
|
|
211
|
+
const delimiters = this.options.sentenceDelimiters;
|
|
212
|
+
const minChars = this.options.minCharsBeforeSpeak;
|
|
213
|
+
let lastSplit = 0;
|
|
214
|
+
for (let i = 0; i < this.buffer.length; i++) {
|
|
215
|
+
if (delimiters.includes(this.buffer[i])) {
|
|
216
|
+
const sentence = this.buffer.substring(lastSplit, i + 1).trim();
|
|
217
|
+
if (sentence.length >= minChars) {
|
|
218
|
+
this.enqueue(sentence);
|
|
219
|
+
lastSplit = i + 1;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Keep un-split remainder in the buffer
|
|
224
|
+
if (lastSplit > 0) {
|
|
225
|
+
this.buffer = this.buffer.substring(lastSplit);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Submit a sentence directly to the browser's native speech queue.
|
|
230
|
+
* The browser pre-processes queued utterances so the next one starts
|
|
231
|
+
* immediately when the current one finishes — no gap between sentences.
|
|
232
|
+
*/
|
|
233
|
+
enqueue(text) {
|
|
234
|
+
if (!BrowserSpeechSynthesizer.isSupported())
|
|
235
|
+
return;
|
|
236
|
+
const trimmed = text.trim();
|
|
237
|
+
if (!trimmed)
|
|
238
|
+
return;
|
|
239
|
+
// Chrome workaround: cancel any stale/paused state before first speak
|
|
240
|
+
if (!this.warmedUp) {
|
|
241
|
+
window.speechSynthesis.cancel();
|
|
242
|
+
this.warmedUp = true;
|
|
243
|
+
}
|
|
244
|
+
const utterance = this.createUtterance(trimmed);
|
|
245
|
+
this._pendingCount++;
|
|
246
|
+
utterance.onstart = () => {
|
|
247
|
+
this._isSpeaking = true;
|
|
248
|
+
this.startKeepAlive();
|
|
249
|
+
this.callbacks.onSpeakStart?.(trimmed);
|
|
250
|
+
};
|
|
251
|
+
utterance.onend = () => {
|
|
252
|
+
this._pendingCount--;
|
|
253
|
+
this.callbacks.onSpeakEnd?.(trimmed);
|
|
254
|
+
if (this._pendingCount <= 0) {
|
|
255
|
+
this._pendingCount = 0;
|
|
256
|
+
this._isSpeaking = false;
|
|
257
|
+
this.stopKeepAlive();
|
|
258
|
+
this.callbacks.onQueueEmpty?.();
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
utterance.onerror = (event) => {
|
|
262
|
+
this._pendingCount--;
|
|
263
|
+
if (this._pendingCount <= 0) {
|
|
264
|
+
this._pendingCount = 0;
|
|
265
|
+
this._isSpeaking = false;
|
|
266
|
+
this.stopKeepAlive();
|
|
267
|
+
}
|
|
268
|
+
this.callbacks.onError?.(new Error(`SpeechSynthesis error: ${event.error}`));
|
|
269
|
+
};
|
|
270
|
+
window.speechSynthesis.speak(utterance);
|
|
271
|
+
}
|
|
272
|
+
createUtterance(text) {
|
|
273
|
+
const cleaned = BrowserSpeechSynthesizer.stripMarkdown(text);
|
|
274
|
+
const voice = this.resolveVoice();
|
|
275
|
+
const utterance = new SpeechSynthesisUtterance(cleaned);
|
|
276
|
+
// Set voice BEFORE lang — Chrome requires this order
|
|
277
|
+
if (voice) {
|
|
278
|
+
utterance.voice = voice;
|
|
279
|
+
utterance.lang = voice.lang; // use the voice's own lang tag for consistency
|
|
280
|
+
}
|
|
281
|
+
else if (this.options.lang) {
|
|
282
|
+
utterance.lang = this.options.lang;
|
|
283
|
+
}
|
|
284
|
+
utterance.rate = this.options.rate;
|
|
285
|
+
utterance.pitch = this.options.pitch;
|
|
286
|
+
utterance.volume = this.options.volume;
|
|
287
|
+
return utterance;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Normalize a BCP-47 lang code: lowercase and replace underscores with hyphens.
|
|
291
|
+
*/
|
|
292
|
+
static normalizeLang(lang) {
|
|
293
|
+
return lang.toLowerCase().replace(/_/g, '-');
|
|
294
|
+
}
|
|
295
|
+
resolveVoice() {
|
|
296
|
+
if (this.voiceResolved)
|
|
297
|
+
return this.resolvedVoice;
|
|
298
|
+
const voices = BrowserSpeechSynthesizer.getVoices();
|
|
299
|
+
if (voices.length === 0)
|
|
300
|
+
return null; // voices not loaded yet — do NOT cache, retry next time
|
|
301
|
+
// Try by exact name
|
|
302
|
+
if (this.options.voiceName) {
|
|
303
|
+
const byName = voices.find(v => v.name.toLowerCase().includes(this.options.voiceName.toLowerCase()));
|
|
304
|
+
if (byName) {
|
|
305
|
+
this.voiceResolved = true;
|
|
306
|
+
this.resolvedVoice = byName;
|
|
307
|
+
return byName;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// Try by language (exact match, then base language match).
|
|
311
|
+
// When preferLocalVoice is true, search local voices first (no network latency).
|
|
312
|
+
if (this.options.lang) {
|
|
313
|
+
const targetLang = BrowserSpeechSynthesizer.normalizeLang(this.options.lang);
|
|
314
|
+
const targetBase = targetLang.split('-')[0];
|
|
315
|
+
const preferLocal = this.options.preferLocalVoice;
|
|
316
|
+
// Sort: local voices first when preferred
|
|
317
|
+
const sorted = preferLocal
|
|
318
|
+
? [...voices].sort((a, b) => (b.localService ? 1 : 0) - (a.localService ? 1 : 0))
|
|
319
|
+
: voices;
|
|
320
|
+
// Exact match: it-it === it-it
|
|
321
|
+
const exact = sorted.find(v => BrowserSpeechSynthesizer.normalizeLang(v.lang) === targetLang);
|
|
322
|
+
if (exact) {
|
|
323
|
+
this.voiceResolved = true;
|
|
324
|
+
this.resolvedVoice = exact;
|
|
325
|
+
return exact;
|
|
326
|
+
}
|
|
327
|
+
// Base language match: it-it starts with it, it-ch starts with it
|
|
328
|
+
const byBase = sorted.find(v => BrowserSpeechSynthesizer.normalizeLang(v.lang).startsWith(targetBase + '-')) ?? sorted.find(v => BrowserSpeechSynthesizer.normalizeLang(v.lang) === targetBase);
|
|
329
|
+
if (byBase) {
|
|
330
|
+
this.voiceResolved = true;
|
|
331
|
+
this.resolvedVoice = byBase;
|
|
332
|
+
return byBase;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
// Don't cache failure — voices may load later or lang may change
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Chrome workaround: keeps speech synthesis alive.
|
|
340
|
+
* Chrome auto-pauses `speechSynthesis` after ~15 seconds of continuous speech.
|
|
341
|
+
* Calling `pause()` then `resume()` periodically resets this internal timer.
|
|
342
|
+
*/
|
|
343
|
+
startKeepAlive() {
|
|
344
|
+
if (this.keepAliveTimer)
|
|
345
|
+
return; // already running
|
|
346
|
+
this.keepAliveTimer = setInterval(() => {
|
|
347
|
+
if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {
|
|
348
|
+
window.speechSynthesis.pause();
|
|
349
|
+
window.speechSynthesis.resume();
|
|
350
|
+
}
|
|
351
|
+
}, 10_000);
|
|
352
|
+
}
|
|
353
|
+
/** Stop the Chrome keepalive timer. */
|
|
354
|
+
stopKeepAlive() {
|
|
355
|
+
if (this.keepAliveTimer) {
|
|
356
|
+
clearInterval(this.keepAliveTimer);
|
|
357
|
+
this.keepAliveTimer = null;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Strip common Markdown formatting so TTS reads only the plain text.
|
|
362
|
+
* Handles: bold, italic, strikethrough, inline code, code blocks,
|
|
363
|
+
* headers, links, images, blockquotes, list markers, horizontal rules.
|
|
364
|
+
*/
|
|
365
|
+
static stripMarkdown(text) {
|
|
366
|
+
return text
|
|
367
|
+
// Code blocks (```...```)
|
|
368
|
+
.replace(/```[\s\S]*?```/g, '')
|
|
369
|
+
// Inline code (`...`)
|
|
370
|
+
.replace(/`([^`]+)`/g, '$1')
|
|
371
|
+
// Images 
|
|
372
|
+
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
373
|
+
// Links [text](url)
|
|
374
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
375
|
+
// Bold+Italic ***text*** or ___text___
|
|
376
|
+
.replace(/(\*{3}|_{3})(.+?)\1/g, '$2')
|
|
377
|
+
// Bold **text** or __text__
|
|
378
|
+
.replace(/(\*{2}|_{2})(.+?)\1/g, '$2')
|
|
379
|
+
// Italic *text* or _text_
|
|
380
|
+
.replace(/(\*|_)(.+?)\1/g, '$2')
|
|
381
|
+
// Strikethrough ~~text~~
|
|
382
|
+
.replace(/~~(.+?)~~/g, '$1')
|
|
383
|
+
// Headers # ... ######
|
|
384
|
+
.replace(/^#{1,6}\s+/gm, '')
|
|
385
|
+
// Blockquotes > text
|
|
386
|
+
.replace(/^>+\s?/gm, '')
|
|
387
|
+
// Unordered list markers (- * +)
|
|
388
|
+
.replace(/^[\s]*[-*+]\s+/gm, '')
|
|
389
|
+
// Ordered list markers (1. 2. etc.)
|
|
390
|
+
.replace(/^[\s]*\d+\.\s+/gm, '')
|
|
391
|
+
// Horizontal rules (---, ***, ___)
|
|
392
|
+
.replace(/^[-*_]{3,}\s*$/gm, '')
|
|
393
|
+
// HTML tags
|
|
394
|
+
.replace(/<[^>]+>/g, '')
|
|
395
|
+
// Collapse multiple newlines
|
|
396
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
397
|
+
.trim();
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
exports.BrowserSpeechSynthesizer = BrowserSpeechSynthesizer;
|