Wednesday , December 2 2026
Speech to Text and Text to Speech

Speech to Text and Text to Speech

Updated: 28 November 2026Level: IntermediateReading time: about 12 minutesSpeechRecognition · gTTS · requests

In this tutorial we build a simple voice assistant: it listens to your question (speech to text), decides what to do, and answers aloud (text to speech) – including reading out the latest news headlines.

What You Will Learn

  • Convert speech to text with SpeechRecognition
  • Reply with text to speech
  • Respond to keywords like “name”, “age” and “news”
  • Read news headlines from an API safely
  • Ideas to make it smarter with an LLM

Prerequisites

Text to Speech.

Install

Install
pip install SpeechRecognition pyaudio gTTS pygame requests
Note: On Windows, if pyaudio fails to install, try pip install pipwin then pipwin install pyaudio, or use a recent wheel. On Linux install portaudio19-dev first.

Step 1: Speak

Example
import os
import pygame
from gtts import gTTS

pygame.mixer.init()

def speak(text):
    print("Assistant:", text)
    gTTS(text, lang="en", tld="co.in").save("reply.mp3")
    pygame.mixer.music.load("reply.mp3")
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        pygame.time.wait(100)
    pygame.mixer.music.unload()
    os.remove("reply.mp3")

Explanation: The function saves the reply as an MP3, plays it to the end, then deletes the file so the next reply can reuse the name.

Step 2: Listen

Example
import speech_recognition as sr

def listen():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source, duration=0.5)
        print("Listening...")
        audio = r.listen(source)
    try:
        return r.recognize_google(audio, language="en-IN").lower()
    except sr.UnknownValueError:
        return ""

Explanation: recognize_google uses Google’s free web speech API (internet needed). language="en-IN" understands Indian English and much Hinglish; use "hi-IN" for Hindi.

Step 3: News Headlines

Example
import os, requests

def get_headlines(n=3):
    key = os.environ["NEWS_API_KEY"]                 # never hard-code keys
    r = requests.get("https://newsapi.org/v2/top-headlines",
                     params={"country": "in", "pageSize": n, "apiKey": key}, timeout=10)
    articles = r.json().get("articles", [])
    return [f"{a['source']['name']}: {a['title']}" for a in articles]

Explanation: Get a free key from a news API provider and store it in an environment variable. The previous version of this tutorial had an API key written inside the URL – anyone reading the page could use it. Check the provider’s current terms, because free plans and supported countries change.

Step 4: The Assistant Loop

Example
def handle(command):
    words = command.split()
    if "name" in words:
        speak("My name is ML Assistant from machine learning dot org dot in.")
    elif "age" in words:
        speak("I was created this year, so I am still very young!")
    elif "news" in words:
        headlines = get_headlines()
        if not headlines:
            speak("Sorry, I could not get the news right now.")
        for i, h in enumerate(headlines, 1):
            speak(f"News {i}. {h}")
    elif command:
        speak("Sorry, I can tell you my name, my age or the news.")

speak("Hello! How can I help you?")
while True:
    command = listen()
    print("You:", command)
    if any(w in command for w in ("stop", "bye", "exit")):
        speak("Goodbye!")
        break
    handle(command)
Output
Assistant: Hello! How can I help you?
Listening...
You: aaj ki news suna do
Assistant: News 1. <source>: <headline>
Assistant: News 2. <source>: <headline>
Assistant: News 3. <source>: <headline>

Explanation: Saying “aaj ki news suna do” contains the word “news”, so the assistant reads three headlines. Headlines change every day, so your output will be different.

Make It Smarter

  • Send any other question to an LLM with the OpenAI, Gemini or Claude API and speak the answer.
  • Add tools (weather, calendar) to turn it into an AI agent.
  • Use offline speech recognition (Vosk or Whisper) for privacy.

Common Errors

Problem Cause and fix
OSError: No Default Input Device No microphone found – check the device and permissions.
Always returns an empty string Speak closer to the microphone; increase ambient-noise adjustment.
KeyError: NEWS_API_KEY Set the environment variable before running.

Series

NLP series: Introduction · Tokenizer · Stop Words · Stemming · Lemmatization · WordNet · NLTK Practice · Spam Detection Project · Text to Speech · Speech Assistant · NLP Project Ideas

Interview Questions

Q: What are the parts of a voice assistant?
Speech-to-text, understanding/decision (rules or an LLM), and text-to-speech.

Practice Exercises

  1. Add a “time” command that speaks the current time.
  2. Make it answer in Hindi when the question is in Hindi.
  3. Connect unknown questions to an LLM.

Summary

A voice assistant listens with SpeechRecognition, decides with simple rules or an LLM, and replies with gTTS. Keep API keys in environment variables.

Next: NLP Project Ideas · AI Agents

About Machine Learning

Check Also

Word Embeddings and Word2Vec Explained (with Python)

Word embeddings and Word2Vec explained: embeddings from co-occurrence and SVD in tested NumPy, CBOW vs skip-gram, gensim training and contextual embeddings.