Create a TTS (Text to Speech) play button in Javascript

 Add an event listener to the play button that starts the speech synthesis when clicked

<div id="show"></div>

<script>

  // text to play
  const greeting = "How are you?";

  // Create a new SpeechSynthesisUtterance object
  const synth = new SpeechSynthesisUtterance();
  synth.text = greeting;

  // Create a play button element
  const playButton = document.createElement('button');
  playButton.textContent = 'Play';

  // Add an event listener to the play button that starts the speech synthesis when clicked
  playButton.addEventListener('click', function() {
    speechSynthesis.speak(synth);
  });

  const element = document.getElementById('show');
  element.innerHTML = '';
  element.appendChild(playButton);
  element.appendChild(document.createTextNode(greeting));
</script>

Post a Comment