This repository has been archived on 2024-10-01. You can view files and clone it, but cannot push or open issues or pull requests.
ai-virtual-assistant/py/voice_recognition.py

31 lines
1.2 KiB
Python

import speech_recognition as sr
class Voice: #create Class
@staticmethod
def listen(): #define function listen()
recognizer = sr.Recognizer()
try:
with sr.Microphone() as source:
print("Adjusting for ambient noise...")
recognizer.adjust_for_ambient_noise(source, duration=0.5) #listen to surrounding for .5sec to adjust backgroundnoise
print("Listening...")
audio_data = recognizer.listen(source) #listen to user until user stops speaking
print("Audio captured")
try:
text = recognizer.recognize_sphinx(audio_data) # Using Sphinx convert audio to text (also works offline)
#if any Exceptions or Errors eccur => return ERROR
except sr.UnknownValueError:
text = "ERROR"
except sr.RequestError as e:
text = "ERROR"
except sr.RequestError as e:
text = "ERROR"
except sr.UnknownValueError:
text = "ERROR"
except Exception as e:
text = "ERROR"
return text