ai-virtual-assistant/py/voice_recognition.py

32 lines
1.2 KiB
Python
Raw Normal View History

2024-09-16 14:38:45 +02:00
import speech_recognition as sr
2024-09-16 15:15:00 +02:00
class Voice: #create Class
2024-09-16 14:38:45 +02:00
@staticmethod
2024-09-16 15:15:00 +02:00
def listen(): #define function listen()
2024-09-16 14:38:45 +02:00
recognizer = sr.Recognizer()
try:
with sr.Microphone() as source:
print("Adjusting for ambient noise...")
2024-09-16 15:15:00 +02:00
recognizer.adjust_for_ambient_noise(source, duration=0.5) #listen to surrounding for .5sec to adjust backgroundnoise
2024-09-16 14:38:45 +02:00
print("Listening...")
2024-09-16 15:15:00 +02:00
audio_data = recognizer.listen(source) #listen to user until user stops speaking
2024-09-16 14:38:45 +02:00
print("Audio captured")
try:
2024-09-16 15:15:00 +02:00
text = recognizer.recognize_sphinx(audio_data) # Using Sphinx convert audio to text (also works offline)
#if any Exceptions or Errors eccur => return ERROR
2024-09-16 14:38:45 +02:00
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
2024-09-16 14:28:41 +02:00