Skip to content

Instantly share code, notes, and snippets.

@mainendra
Last active March 13, 2024 14:53
Show Gist options
  • Save mainendra/cafb682359ab506f2a9766e6b87d8275 to your computer and use it in GitHub Desktop.
Save mainendra/cafb682359ab506f2a9766e6b87d8275 to your computer and use it in GitHub Desktop.
TTS engine
const synth = window.speechSynthesis;
let currentReadoutStrings: string[] = [];
let currentAlertStrings: string[] = [];
let currentSSU: SpeechSynthesisUtterance;
function reset(): void {
currentReadoutStrings = [];
currentAlertStrings = [];
}
function getNextReadoutString(): string {
if (currentAlertStrings.length > 0) {
return currentAlertStrings[0];
}
return currentReadoutStrings[0];
}
function removeLastReadoutString(): void {
if (currentAlertStrings.length > 0) {
currentAlertStrings.shift();
return;
}
currentReadoutStrings.shift();
}
function speak(readoutStrings: string[]): void {
currentReadoutStrings = readoutStrings;
if (currentAlertStrings.length === 0) {
stop();
read();
}
}
function interruptAndSpeak(readoutStrings: string[]): void {
stop();
currentAlertStrings = readoutStrings;
read();
}
function appendAndSpeak(readoutStrings: string[]): void {
if (currentReadoutStrings.length === 0) {
speak(readoutStrings);
} else {
currentReadoutStrings = currentReadoutStrings.concat(readoutStrings);
}
}
function stop(): void {
if (currentSSU) {
currentSSU.onend = () => {};
}
synth.cancel();
}
function read(): void {
const nextReadoutString = getNextReadoutString();
if (nextReadoutString === undefined) {
return;
}
currentSSU = new SpeechSynthesisUtterance(nextReadoutString);
currentSSU.onend = () => {
removeLastReadoutString();
read();
};
synth.speak(currentSSU);
}
export {
speak,
appendAndSpeak,
interruptAndSpeak,
stop,
reset,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment