I'm new to JavaScript and I am trying to add a pause button by linking a button to synth.pause(speakText); where const synth = window.speechSynthesis; and const speakText = new SpeechSynthesisUtterance(textInput.value);.
I can't make speakText accessible to the pause function since I construct my speakText object in my speak() function. I tried making speakText a global variable by calling its constructor outside of the function but that causes speak() to throw an error.
Any idea on how I can achieve this?
JS Code:
//Speak
const speak = () => {
//Check to see if already speaking
if (synth.speaking && state === "play") {
console.error("Already speaking");
state = "paused";
console.log("state: " + state);
return;
}
//Make sure there is some input
if (textInput.value !== "" && state === "stop") {
const speakText = new SpeechSynthesisUtterance(textInput.value);
state = "play";
//Speak error
speakText.onerror = e => {
console.log("Something went wrong!");
};
//Selected voice
const selectedVoice = voiceSelect.selectedOptions[0].getAttribute(
"data-name"
);
//Loop through voices to set the correct voice
voices.forEach(voice => {
if (selectedVoice === voice.name) {
speakText.voice = voice;
}
});
//Set the rate and pitch
speakText.rate = rate.value;
speakText.pitch = pitch.value;
//Speak end
speakText.onend = e => {
console.log("Done Speaking");
state = "stop";
};
speakController(speakText);
}
};
const speakController = speakText => {
console.log("state: " + state);
if (state === "play") {
synth.speak(speakText);
} else if (state === "pause") {
synth.pause(speakText);
} else if (state === "stop") {
synth.cancel(speakText);
}
};
//----------EVENT LISTENERS----------
var state = "stop";
// Text form submit
textForm.addEventListener("submit", e => {
e.preventDefault();
speak();
textInput.blur();
});
//Pause button
pauseButton.addEventListener("onClick", e => {
e.preventDefault();
speakController;
});