IAmSalvaMartini

Python Speech-to-Text

Oct 13th, 2021
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. import speech_recognition as sr
  2. import pyttsx3
  3.  
  4. # Initialize the recognizer
  5. r = sr.Recognizer()
  6.  
  7. # Function to convert text to
  8. # speech
  9. def SpeakText(command):
  10.    
  11.     # Initialize the engine
  12.     engine = pyttsx3.init()
  13.     engine.say(command)
  14.     engine.runAndWait()
  15.    
  16.    
  17. # Loop infinitely for user to
  18. # speak
  19.  
  20. while(1):  
  21.    
  22.     # Exception handling to handle
  23.     # exceptions at the runtime
  24.     try:
  25.        
  26.         # use the microphone as source for input.
  27.         with sr.Microphone() as source2:
  28.            
  29.             # wait for a second to let the recognizer
  30.             # adjust the energy threshold based on
  31.             # the surrounding noise level
  32.             r.adjust_for_ambient_noise(source2, duration=0.2)
  33.            
  34.             #listens for the user's input
  35.             audio2 = r.listen(source2)
  36.            
  37.             # Using google to recognize audio
  38.             MyText = r.recognize_google(audio2)
  39.             MyText = MyText.lower()
  40.  
  41.             print("Did you say "+MyText)
  42.             SpeakText(MyText)
  43.            
  44.     except sr.RequestError as e:
  45.         print("Could not request results; {0}".format(e))
  46.        
  47.     except sr.UnknownValueError:
  48.         print("unknown error occured")
  49.  
Advertisement
Add Comment
Please, Sign In to add comment