|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Speech Synthesis</title> |
| 6 | + <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> |
| 7 | + <link rel="stylesheet" href="style.css"> |
| 8 | +</head> |
| 9 | +<body> |
| 10 | + |
| 11 | + <div class="voiceinator"> |
| 12 | + |
| 13 | + <h1>The Voiceinator 5000</h1> |
| 14 | + |
| 15 | + <select name="voice" id="voices"> |
| 16 | + <option value="">Select A Voice</option> |
| 17 | + </select> |
| 18 | + |
| 19 | + <label for="rate">Rate:</label> |
| 20 | + <input name="rate" type="range" min="0" max="3" value="1" step="0.1"> |
| 21 | + |
| 22 | + <label for="pitch">Pitch:</label> |
| 23 | + |
| 24 | + <input name="pitch" type="range" min="0" max="2" step="0.1"> |
| 25 | + <textarea name="text">Hello! I love JavaScript 👍</textarea> |
| 26 | + <button id="stop">Stop!</button> |
| 27 | + <button id="speak">Speak</button> |
| 28 | + |
| 29 | + </div> |
| 30 | + |
| 31 | +<script> |
| 32 | + const msg = new SpeechSynthesisUtterance(); |
| 33 | + let voices = []; |
| 34 | + const voicesDropdown = document.querySelector('[name="voice"]'); |
| 35 | + const options = document.querySelectorAll('[type="range"], [name="text"]'); |
| 36 | + const speakButton = document.querySelector('#speak'); |
| 37 | + const stopButton = document.querySelector('#stop'); |
| 38 | + |
| 39 | + msg.text = document.querySelector('[name="text"]').value |
| 40 | + |
| 41 | + function populateVoices() { |
| 42 | + voices = this.getVoices() |
| 43 | + voicesDropdown.innerHTML = voices |
| 44 | + .map(voice => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`) |
| 45 | + .join('') |
| 46 | + } |
| 47 | + |
| 48 | + function setVoice() { |
| 49 | + msg.voice = voices.find(voice => voice.name === this.value) |
| 50 | + toggle() |
| 51 | + } |
| 52 | + |
| 53 | + function toggle(startOver=true) { |
| 54 | + speechSynthesis.cancel() |
| 55 | + if (startOver) speechSynthesis.speak(msg) |
| 56 | + } |
| 57 | + |
| 58 | + function setOption() { |
| 59 | + msg[this.name] = this.value |
| 60 | + toggle() |
| 61 | + } |
| 62 | + |
| 63 | + speechSynthesis.addEventListener('voiceschanged', populateVoices) |
| 64 | + voicesDropdown.addEventListener('change', setVoice) |
| 65 | + speakButton.addEventListener('click', toggle) |
| 66 | + stopButton.addEventListener('click', () => toggle(false)) |
| 67 | + options.forEach(option => option.addEventListener('change', setOption)) |
| 68 | +</script> |
| 69 | + |
| 70 | +</body> |
| 71 | +</html> |
0 commit comments