Below is my attempt to to make text to speech that will read text that is in the body tag.
<body id="readText">
Read everything
<button onclick="textToSpeech
()">Speak</button>
</body>
<script>
function textToSpeech() {
let text = document.getElementById('readText').value;
let speech = new SpeechSynthesisUtterance();
speech.text = text;
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
</script>
Each time I run it, I keep hearing ‘undefined’, what did I do wrong please?
-
The body element does not have a .value
property. That is for input elements.
-
You want to use text
for the SpeechSynthesisUtterance
constructor and pass that object to the speak
method
<body id="readText">
Read everything
<button onclick="textToSpeech()">Speak</button>
</body>
<script>
function textToSpeech() {
let text = document.getElementById('readText').innerText;
let speech = new SpeechSynthesisUtterance(text);
speech.text = text;
speech.volume = 1;
speech.rate = 1;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
</script>
1 Like