| 148 | } |
| 149 | |
| 150 | const speak = () => { |
| 151 | // Check if speaking |
| 152 | if (synth.speaking) { |
| 153 | console.error('Already speaking...'); |
| 154 | return; |
| 155 | } |
| 156 | if (textInput.value !== '') { |
| 157 | // Add background animation |
| 158 | afterEffect.style.background = '#141414 url(../assets/Images/TextToSpeech/wave.gif)'; |
| 159 | afterEffect.style.backgroundRepeat = 'repeat-x'; |
| 160 | afterEffect.style.backgroundSize = '100% 100%'; |
| 161 | |
| 162 | // Get speak text |
| 163 | const speakTextt = new SpeechSynthesisUtterance(textInput.value); |
| 164 | |
| 165 | // Speak end |
| 166 | speakTextt.onend = e => { |
| 167 | console.log('Done speaking...'); |
| 168 | afterEffect.style.background = '#333'; |
| 169 | }; |
| 170 | |
| 171 | // Speak error |
| 172 | speakTextt.onerror = e => { |
| 173 | console.error('Something went wrong'); |
| 174 | }; |
| 175 | |
| 176 | // Selected voice |
| 177 | const selectedVoice = voiceSelect.selectedOptions[0].getAttribute( |
| 178 | 'data-name' |
| 179 | ); |
| 180 | |
| 181 | // Loop through voices |
| 182 | voices.forEach(voice => { |
| 183 | if (voice.name === selectedVoice) { |
| 184 | speakTextt.voice = voice; |
| 185 | } |
| 186 | }); |
| 187 | |
| 188 | // Set pitch and rate |
| 189 | speakTextt.rate = rate.value; |
| 190 | speakTextt.pitch = pitch.value; |
| 191 | // Speak |
| 192 | synth.speak(speakTextt); |
| 193 | } |
| 194 | }; |
| 195 | |
| 196 | // EVENT LISTENERS |
| 197 | readBtn.addEventListener('click', e => { |