-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
42 lines (34 loc) · 1.32 KB
/
script.js
File metadata and controls
42 lines (34 loc) · 1.32 KB
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
// Declare the speech object
let speech = new SpeechSynthesisUtterance();
// Declare the voices array
let voices = [];
// Get the select element
let voiceSelect = document.querySelector("select");
// Wait for voices to be loaded
window.speechSynthesis.onvoiceschanged = () => {
voices = window.speechSynthesis.getVoices(); // Get available voices
speech.voice = voices[0]; // Set default voice
// Clear existing options in the dropdown
voiceSelect.innerHTML = "";
// Populate the dropdown with available voices
voices.forEach((voice, i) => {
voiceSelect.options[i] = new Option(voice.name, i); // Use "Option" (case-sensitive)
});
};
// Optional: Call getVoices() immediately in case voices are already loaded
voices = window.speechSynthesis.getVoices();
if (voices.length > 0) {
speech.voice = voices[0];
voices.forEach((voice, i) => {
voiceSelect.options[i] = new Option(voice.name, i);
});
}
// Add event listener to handle voice selection change
voiceSelect.addEventListener("change", () => {
speech.voice = voices[voiceSelect.value];
});
// Add event listener to handle button click for speaking
document.querySelector("button").addEventListener("click", () => {
speech.text = document.querySelector("textarea").value; // Get text from textarea
window.speechSynthesis.speak(speech); // Speak the text
});