Convertor πŸŽ™οΈ Text ↔ Speech Converter

by Vijay Pancholi

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Text ↔ Speech Converter</title>
</head>
<body>

  <h1>πŸŽ™οΈ Text ↔ Speech Converter</h1>
  
  <textarea id="textArea" placeholder="Type here or click '🎀 Speak' to start voice..."></textarea>

  <div class="btns">
    <button onclick="speakText()">πŸ—£οΈ Speak Text</button>
    <button onclick="startListening()">🎀 Speak (Voice β†’ Text)</button>
  </div>

  <div class="note">Note: Voice recognition works best in Google Chrome.</div>

</body>
</html>

CSS

body {
      font-family: 'Segoe UI', sans-serif;
      padding: 40px;
      background: #f4f9ff;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    h1 {
      color: #333;
    }

    textarea {
      width: 100%;
      max-width: 500px;
      height: 150px;
      font-size: 1.1rem;
      padding: 15px;
      margin-top: 20px;
      border-radius: 10px;
      border: 1px solid #ccc;
      resize: none;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .btns {
      margin-top: 20px;
      display: flex;
      gap: 20px;
    }

    button {
      padding: 10px 20px;
      border: none;
      font-size: 1rem;
      border-radius: 6px;
      cursor: pointer;
      background-color: #4caf50;
      color: white;
      transition: background 0.3s;
    }

    button:hover {
      background-color: #388e3c;
    }

    .note {
      margin-top: 20px;
      font-size: 0.9rem;
      color: #666;
    }

JavaScript

// TEXT β†’ SPEECH
    function speakText() {
      const text = document.getElementById("textArea").value;
      if (text.trim() === "") return alert("Please enter some text!");

      const speech = new SpeechSynthesisUtterance(text);
      speech.lang = "en-US";
      speech.rate = 1;
      speech.pitch = 1;
      speechSynthesis.speak(speech);
    }

    // SPEECH β†’ TEXT
    function startListening() {
      const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
      recognition.lang = 'en-US';
      recognition.interimResults = false;
      recognition.maxAlternatives = 1;
      alert("Please allow microphone access when prompted.");
      recognition.start();

      recognition.onresult = function(event) {
        const spokenText = event.results[0][0].transcript;
        document.getElementById("textArea").value = spokenText;
      };

      recognition.onerror = function(event) {
        alert("Error occurred: " + event.error);
      };
    }