Sitemap
Uche Blessed

Uche Blessed

Developer Relations & Software Engineer writing clear, practical content on C#, .NET, Python, JavaScript, and SQL for the developer community.

Creating a Speech-to-Text Software Using Python

3 min readMar 26, 2024

--

Press enter or click to view image in full size

Introduction

Speech-to-text (STT) conversion is a useful technique that allows a computer to transcribe spoken words into text. This can be used in various applications, such as voice-controlled assistants, transcription services, and more. In this article, we’ll explore how to create a simple speech-to-text application in Python using the SpeechRecognition library.

Prerequisites

Before we begin, make sure you have Python installed on your system. You’ll also need to install the SpeechRecognition library, which can be done using pip.

Step 1: Install the Required Libraries

Install the SpeechRecognition and PyAudio library using pip:

pip install SpeechRecognition

pip install PyAudio

Step 2: Set Up Your Python Script

Create a new Python script (e.g., speech_to_text.py) and open it in your favorite code editor.

  • We start by importing the speech_recognition module and aliasing it as sr for ease of use.
import speech_recognition as sr
  • We define a function speech_to_text that will contain our speech-to-text logic. Inside the function, we create a Recognizer object from sr.
def speech_to_text():
recognizer = sr.Recognizer()
  • We use a context manager (with) to open the microphone (Microphone) as the source of audio input.
  • We print a prompt asking the user to say something.
  • We adjust for ambient noise to improve recognition accuracy.
  • We use the listen method of the Recognizer object to capture audio input from the microphone for up to 5 seconds (timeout=5).

Get Uche Blessed’s stories in your inbox

Join Medium for free to get updates from this writer.

with sr.Microphone() as source:
print("Say something:")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source, timeout=5)
  • We use a try block to attempt to recognize the audio input using Google's Web Speech API (recognize_google method).
  • If the recognition is successful, we print the transcribed text.
  • If the recognition fails (UnknownValueError), we print an error message indicating that the audio could not be understood.
  • If there is an error connecting to the Google API (RequestError), we print an error message with the details of the error.
    try:
print("Recognizing...")
text = recognizer.recognize_google(audio)
print(f"Text: {text}")
except sr.UnknownValueError:
print("Could not understand audio.")
except sr.RequestError as e:
print(f"Error connecting to Google API: {e}")
  • To save the transcribed text to a .txt file, you can modify the speech_to_text function to write the text to a file after it has been recognized. Here's an updated version of the code that saves the text to a file named transcribed_text.txt:
with open("transcribed_text.txt", "w") as file:
file.write(text)
print("Transcribed text saved to transcribed_text.txt")
  • Finally, we use the if __name__ == "__main__": block to ensure that the speech_to_text function is called when the script is run as the main program.
if __name__ == "__main__":
speech_to_text()

Here’s the complete code for our speech-to-text application:

import speech_recognition as sr

def speech_to_text_and_save():
recognizer = sr.Recognizer()

with sr.Microphone() as source:
print("Say something:")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source, timeout=5)

try:
print("Recognizing...")
text = recognizer.recognize_google(audio)
print(f"Text: {text}")

with open("transcribed_text.txt", "w") as file:
file.write(text)
print("Transcribed text saved to transcribed_text.txt")
except sr.UnknownValueError:
print("Could not understand audio.")
except sr.RequestError as e:
print(f"Error connecting to Google API: {e}")

if __name__ == "__main__":
speech_to_text_and_save()

Step 3: Run the Code

Save the code to a file (e.g., speech_to_text.py) and run it via your terminal/cmd.

Step 4: Speak Into Your Microphone

When you run the script, it will prompt you to speak into your microphone. Speak clearly, make sure you have a microphone connected to your computer and the script will transcribe your speech to text using Google’s Web Speech API.

Step 5: Check the Output

After speaking, the transcribed text will be saved to a file named transcribed_text.txt in the same directory as your Python script.

Conclusion

In this tutorial, you learned how to create a simple speech-to-text application in Python that saves transcribed text to a .txt file. This project can be a great starting point for further exploration into speech recognition and natural language processing. Experiment with different settings, try other recognition engines, and explore how to improve the accuracy and functionality of your speech-to-text software.

--

--

Uche Blessed
Uche Blessed

Developer Relations & Software Engineer writing clear, practical content on C#, .NET, Python, JavaScript, and SQL for the developer community.