HTML code script for a Text to speech

Created on 3 July, 2024 • 119 views

HTML code script for a Text to speech

<!DOCTYPE html>

<html lang="en">

<head>

 <meta charset="UTF-8">

 <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <title>Text to Speech</title>

</head>

<body>

 <h1>Text to Speech Converter</h1>

 <div id="text-container">

  <textarea id="text-input" rows="5" placeholder="Enter text here"></textarea>

  <button id="speak-button">Convert to Speech</button>

 </div>

 <script>

 const textInput = document.getElementById("text-input");

 const speakButton = document.getElementById("speak-button");


 speakButton.addEventListener("click", () => {

  const speechSynthesis = window.speechSynthesis;

  if (speechSynthesis.speaking) {

   speechSynthesis.cancel();

   return;

  }


  const text = textInput.value;

  if (text.trim() === "") {

   alert("Please enter some text to speak.");

   return;

  }


  const utterance = new SpeechSynthesisUtterance(text);

  speechSynthesis.speak(utterance);

 });

 </script>

</body>

</html>