You can turn speech into text in Python. The SpeechRecognition module talks to the Google speech engine, so it works with any microphone and needs no training.

Scripting is where Python really pays off. The Python Scripting Essentials Bundle has the kind of small automation projects you would build for work.

It needs an internet connection, because the audio is sent to Google to be recognised. The example below records a short clip and prints what it heard.

This page shows how to use Python with Google’s speech engine.

Setting Up the Development Environment

Before you start, install what you need. The SpeechRecognition module works with pyenv, pipenv and virtualenv. For a global install:

pip install SpeechRecognition

Note that that the SpeechRecognition library hinges on pyaudio. The installation methodology for pyaudio might differ based on the operating system. For example, Manjaro Linux users can find packages labeled “python-pyaudio” and “python2-pyaudio”. Always ensure that you’ve selected the appropriate package tailored for your OS.

Introduction to Speech Recognition

Try it with this and see what comes back:

python -m speech_recognition

A Closer Look at Google’s Speech Recognition Engine

Google’s engine in a bit more detail. While this tutorial predominantly showcases its usage in English, note that the engine is proficient in handling many languages.

A one thing to know: this walkthrough employs the standard Google API key. If you’re inclined to integrate an alternate API key, modify the code accordingly:

r.recognize_google(audio, key="YOUR_GOOGLE_SPEECH_RECOGNITION_API_KEY")

Save this as speechtest.py and run it with Python 3:

#!/usr/bin/env python3

import speech_recognition as sr

# Capture audio input from the microphone
r = sr.Recognizer()
with sr.Microphone() as source:
print("Kindly voice out your command!")
audio = r.listen(source)

try:
print("Interpreted as: " + r.recognize_google(audio))
except sr.UnknownValueError:
print("Apologies, the audio wasn't clear enough.")
except sr.RequestError as e:
print("There was an issue retrieving results. Error: {0}".format(e))

Dive Deeper with Downloadable Speech Recognition Samples

The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.