1 min read

Python SpeechRecognition Module

The SpeechRecognition library allows you to convert audio into text. It supports several engines and APIs, including Google Speech Recognition, Sphinx, and OpenAI Whisper.

Installation

pip install SpeechRecognition

To use the microphone input, you also need PyAudio.

# Windows
pip install pyaudio

# Linux (requires portaudio dev headers)
# sudo apt-get install python3-pyaudio

Recognizing from Audio File

import speech_recognition as sr

r = sr.Recognizer()

with sr.AudioFile('audio.wav') as source:
    audio_data = r.record(source)
    text = r.recognize_google(audio_data)
    print(text)

Recognizing from Microphone

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone() as source:
    print("Say something!")
    # Adjust for ambient noise
    r.adjust_for_ambient_noise(source)
    audio = r.listen(source)

    try:
        print("You said: " + r.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print(f"Could not request results from Google Speech Recognition service; {e}")

Supported Engines

  • recognize_bing(): Microsoft Bing Speech
  • recognize_google(): Google Web Speech API
  • recognize_google_cloud(): Google Cloud Speech
  • recognize_houndify(): Houndify by SoundHound
  • recognize_ibm(): IBM Speech to Text
  • recognize_sphinx(): CMU Sphinx (Offline)
  • recognize_whisper(): OpenAI Whisper

programming/python/python