-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
98 lines (80 loc) · 2.37 KB
/
index.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Init SpeechSynth API
const synth = window.speechSynthesis;
// DOM elements
const textForm = document.querySelector("#form");
const textInput = document.querySelector("#text-input");
const voiceSelect = document.querySelector("#voice-select");
const rate = document.querySelector("#rate");
const rateValue = document.querySelector("#rate-value");
const pitch = document.querySelector("#pitch");
const pitchValue = document.querySelector("#pitch-value");
// Init voices array
let voices = [];
const getVoices = () => {
voices = synth.getVoices();
// Loop through voices and create an option for each one
voices.forEach(voice => {
// Create an option element
const option = document.createElement('option');
// Fill the option with voices and lang
option.textContent = voice.name + '(' + voice.lang + ')';
// Set needed option attributes
option.setAttribute("data-lang", voice.lang);
option.setAttribute("data-name", voice.name);
voiceSelect.appendChild(option);
});
};
getVoices();
if (synth.onvoiceschanged !== undefined) {
synth.onvoiceschanged = getVoices;
}
// Speak
const speak = () => {
// Check if speaking
if (synth.speaking) {
console.error("Already Speaking...");
return;
}
if (textInput.value !== "") {
// Get speak text
const speakText = new SpeechSynthesisUtterance(textInput.value);
// Speak end
speakText.onend = (e) => {
console.log("Done speaking...");
};
// Speak error
speakText.onerror = (e) => {
console.error("Something went wrong!");
};
// Selected voice
const selectedVoice =
voiceSelect.selectedOptions[0].getAttribute("data-name");
// Loop through voices
voices.forEach((voice) => {
if (voice.name === selectedVoice) {
speakText.voice = voice;
}
});
// Set pitch and rate
speakText.rate = rate.value;
speakText.pitch = pitch.value;
// Speak
synth.speak(speakText)
}
};
// Event LISTENERS
// Text form submit
textForm.addEventListener("submit",e => {
e.preventDefault();
speak();
textInput.blur();
});
// Rate value change
rate.addEventListener("change",e => rateValue.textContent = rate.value);
// Pitch value change
pitch.addEventListener("change",e => pitchValue.textContent = pitch.value);
// voice select change
voiceSelect.addEventListener("change",e => {
speak()
console.log(speak);
});