Creating a real-time Speech-To-Text (STT) program in Python can be relatively straightforward thanks to modern APIs and services like Google Cloud Speech-to-Text, IBM Watson Speech to Text, or Microsoft Azure Speech. However, if you want a simpler and local version without relying on external services, you can also use libraries like speech_recognition in combination with PyAudio for microphone access.
Here is an example of how you can create a simple STT program using the speech_recognition library:
First, make sure you have installed necessary libraries:
pip install SpeechRecognition
pip install PyAudio # You might need this for microphone input
Then, you might write a script like this:
import speech_recognition as sr
# Initialize recognizer
r = sr.Recognizer()
# Function to convert speech to text
def listen_and_recognize():
# Use the default microphone as the audio source
with sr.Microphone() as source:
print("Listening...")
# Listen for the first phrase and extract it into audio data
try:
# Adjusts the recognizer sensitivity to ambient noise
r.adjust_for_ambient_noise(source, duration=0.5)
audio = r.listen(source)
print("Recognizing...")
# Recognize speech using Google Speech Recognition
text = r.recognize_google(audio)
print("You said: " + text)
except sr.RequestError:
# API was unreachable or unresponsive
print("API unavailable/unresponsive")
except sr.UnknownValueError:
# Speech was unintelligible
print("Unable to recognize speech")
except Exception as e:
print(e)
def main():
try:
while True:
listen_and_recognize()
except KeyboardInterrupt:
print("\nProgram stopped by the user")
exit()
if __name__ == "__main__":
main()
This script continuously listens for speech and then attempts to convert any speech it hears to text using Google's speech recognition API. To stop the program, you can simply interrupt it, for example, by pressing Ctrl+C in your terminal.
Remember, this particular setup requires an active internet connection because the speech_recognition library is using Google's web service to process the audio. If you require a more complex or an offline solution, you might need to integrate with specific APIs that support offline functionality or use a library like Mozilla's DeepSpeech, which can run entirely offline.
Please keep in mind that PyAudio might have compatibility issues with recent Python versions (3.7+), and you may need to use unofficial pre-built binaries or find an alternative solution for accessing the microphone.